summaryrefslogtreecommitdiffstats
path: root/devtools/client/shared/sourceeditor
diff options
context:
space:
mode:
Diffstat (limited to 'devtools/client/shared/sourceeditor')
-rw-r--r--devtools/client/shared/sourceeditor/README259
-rw-r--r--devtools/client/shared/sourceeditor/autocomplete.js358
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/LICENSE23
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/accessibleTextarea.js146
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/comment/comment.js209
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/comment/continuecomment.js78
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/dialog/dialog.css32
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/dialog/dialog.js161
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/display/placeholder.js63
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/edit/closebrackets.js191
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/edit/closetag.js184
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/edit/continuelist.js99
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/edit/matchbrackets.js150
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/edit/matchtags.js66
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/edit/trailingspace.js27
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/fold/brace-fold.js105
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/fold/comment-fold.js59
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/fold/foldcode.js152
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/fold/foldgutter.css20
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/fold/foldgutter.js151
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/fold/indent-fold.js48
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/fold/markdown-fold.js49
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/fold/xml-fold.js184
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/runmode/runmode.js72
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/scroll/annotatescrollbar.js128
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/search/match-highlighter.js165
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/search/matchesonscrollbar.js97
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/search/search.js323
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/search/searchcursor.js293
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/selection/active-line.js72
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/addon/selection/mark-selection.js119
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/cmiframe.html28
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/codemirror.bundle.js1
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/keymap/emacs.js418
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/keymap/sublime.js691
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/keymap/vim.js5494
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/lib/codemirror.css350
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js9788
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/mode/clike/clike.js889
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/mode/clojure/clojure.js292
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/mode/coffeescript/coffeescript.js359
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/mode/css/css.js831
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/mode/elm/elm.js205
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/mode/haxe/haxe.js515
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/mode/htmlmixed/htmlmixed.js152
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/mode/http/http.js113
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/mode/javascript/javascript.js934
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/mode/jsx/jsx.js148
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/mode/rust/rust.js72
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/mode/simple/simple.js216
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/mode/wasm/wasm.js203
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/mode/xml/xml.js413
-rw-r--r--devtools/client/shared/sourceeditor/codemirror/mozilla.css364
-rw-r--r--devtools/client/shared/sourceeditor/codemirror6/codemirror6.bundle.js1
-rw-r--r--devtools/client/shared/sourceeditor/codemirror6/index.mjs22
-rw-r--r--devtools/client/shared/sourceeditor/codemirror6/moz.build12
-rw-r--r--devtools/client/shared/sourceeditor/css-autocompleter.js1248
-rw-r--r--devtools/client/shared/sourceeditor/editor-commands-controller.js97
-rw-r--r--devtools/client/shared/sourceeditor/editor.js1818
-rw-r--r--devtools/client/shared/sourceeditor/moz.build22
-rw-r--r--devtools/client/shared/sourceeditor/package.json26
-rw-r--r--devtools/client/shared/sourceeditor/rollup.config.mjs24
-rw-r--r--devtools/client/shared/sourceeditor/test/CodeMirrorTestActors.sys.mjs49
-rw-r--r--devtools/client/shared/sourceeditor/test/browser.toml70
-rw-r--r--devtools/client/shared/sourceeditor/test/browser_codemirror.js33
-rw-r--r--devtools/client/shared/sourceeditor/test/browser_css_autocompletion.js172
-rw-r--r--devtools/client/shared/sourceeditor/test/browser_css_getInfo.js250
-rw-r--r--devtools/client/shared/sourceeditor/test/browser_css_statemachine.js144
-rw-r--r--devtools/client/shared/sourceeditor/test/browser_detectindent.js99
-rw-r--r--devtools/client/shared/sourceeditor/test/browser_editor_addons.js33
-rw-r--r--devtools/client/shared/sourceeditor/test/browser_editor_alt_b_f.js46
-rw-r--r--devtools/client/shared/sourceeditor/test/browser_editor_autocomplete_basic.js51
-rw-r--r--devtools/client/shared/sourceeditor/test/browser_editor_autocomplete_events.js158
-rw-r--r--devtools/client/shared/sourceeditor/test/browser_editor_basic.js75
-rw-r--r--devtools/client/shared/sourceeditor/test/browser_editor_cursor.js52
-rw-r--r--devtools/client/shared/sourceeditor/test/browser_editor_cursor_blink.js73
-rw-r--r--devtools/client/shared/sourceeditor/test/browser_editor_disableSearchAddon.js38
-rw-r--r--devtools/client/shared/sourceeditor/test/browser_editor_find_again.js217
-rw-r--r--devtools/client/shared/sourceeditor/test/browser_editor_goto_line.js91
-rw-r--r--devtools/client/shared/sourceeditor/test/browser_editor_history.js30
-rw-r--r--devtools/client/shared/sourceeditor/test/browser_editor_markers.js43
-rw-r--r--devtools/client/shared/sourceeditor/test/browser_editor_movelines.js61
-rw-r--r--devtools/client/shared/sourceeditor/test/browser_editor_prefs.js139
-rw-r--r--devtools/client/shared/sourceeditor/test/browser_vimemacs.js13
-rw-r--r--devtools/client/shared/sourceeditor/test/cm_mode_ruby.js285
-rw-r--r--devtools/client/shared/sourceeditor/test/cm_script_injection_test.js10
-rw-r--r--devtools/client/shared/sourceeditor/test/codemirror/codemirror.html213
-rw-r--r--devtools/client/shared/sourceeditor/test/codemirror/comment_test.js114
-rw-r--r--devtools/client/shared/sourceeditor/test/codemirror/doc_test.js371
-rw-r--r--devtools/client/shared/sourceeditor/test/codemirror/driver.js142
-rw-r--r--devtools/client/shared/sourceeditor/test/codemirror/emacs_test.js149
-rw-r--r--devtools/client/shared/sourceeditor/test/codemirror/mode/javascript/test.js513
-rw-r--r--devtools/client/shared/sourceeditor/test/codemirror/mode_test.css23
-rw-r--r--devtools/client/shared/sourceeditor/test/codemirror/mode_test.js193
-rw-r--r--devtools/client/shared/sourceeditor/test/codemirror/multi_test.js295
-rw-r--r--devtools/client/shared/sourceeditor/test/codemirror/search_test.js85
-rw-r--r--devtools/client/shared/sourceeditor/test/codemirror/sublime_test.js284
-rw-r--r--devtools/client/shared/sourceeditor/test/codemirror/test.js2686
-rw-r--r--devtools/client/shared/sourceeditor/test/codemirror/vim_test.js4729
-rw-r--r--devtools/client/shared/sourceeditor/test/codemirror/vimemacs.html215
-rw-r--r--devtools/client/shared/sourceeditor/test/css_autocompletion_tests.json106
-rw-r--r--devtools/client/shared/sourceeditor/test/css_statemachine_testcases.css121
-rw-r--r--devtools/client/shared/sourceeditor/test/css_statemachine_tests.json319
-rw-r--r--devtools/client/shared/sourceeditor/test/head.js195
-rw-r--r--devtools/client/shared/sourceeditor/test/head.xhtml5
-rw-r--r--devtools/client/shared/sourceeditor/wasm.js93
-rw-r--r--devtools/client/shared/sourceeditor/webpack.config.js61
107 files changed, 42973 insertions, 0 deletions
diff --git a/devtools/client/shared/sourceeditor/README b/devtools/client/shared/sourceeditor/README
new file mode 100644
index 0000000000..e4a88f6d4e
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/README
@@ -0,0 +1,259 @@
+This is the CodeMirror editor packaged for the Mozilla Project. CodeMirror
+is a JavaScript component that provides a code editor in the browser. When
+a mode is available for the language you are coding in, it will color your
+code, and optionally help with indentation.
+
+# CodeMirror 6
+
+We're currently migrating to CodeMirror 6, which means we have bundle for version 6 _and_ 5,
+until we successfully migrated all consumers to CodeMirror 6.
+
+For version 6, we're generating a bundle (codemirror6/codemirror6.bundle.js) using rollup.
+The entry point for the bundle is codemirror6/index.mjs, where we export all the classes
+and functions that the editor needs. When adding new exported item, the bundle needs to
+be updated, which can be done by running:
+ > cd devtools/client/shared/sourceeditor
+ > npm install
+ > npm run build-cm6
+
+This will produced a minified bundle, which might not be ideal if you're debugging an issue or profiling.
+You can get an unminified bundle by running:
+> npm run build-cm6-unminified
+
+The generated bundle can be configurated in rollup.config.mjs.
+
+# CodeMirror 5
+
+## CodeMirror 5 Upgrade
+
+Currently used version is 5.58.1. To upgrade: download a new version of
+CodeMirror from the project's page [1] and replace all JavaScript and
+CSS files inside the codemirror directory [2].
+
+Then to recreate codemirror.bundle.js:
+ > cd devtools/client/shared/sourceeditor
+ > npm install
+ > npm run build
+
+When investigating an issue in CodeMirror, you might want to have a non-minified bundle.
+You can do this by running `npm run build-unminified` instead of `npm run build`.
+
+To confirm the functionality run mochitests for the following components:
+
+ * sourceeditor
+ * debugger
+ * styleditor
+ * netmonitor
+ * webconsole
+
+The sourceeditor component contains imported CodeMirror tests [3].
+
+ * Some tests were commented out because we don't use that functionality
+ within Firefox (for example Ruby editing mode). Be careful when updating
+ files test/codemirror.html and test/vimemacs.html; they were modified to
+ co-exist with Mozilla's testing infrastructure. Basically, vimemacs.html
+ is a copy of codemirror.html but only with VIM and Emacs mode tests
+ enabled.
+ * In cm_comment_test.js comment out fallbackToBlock and fallbackToLine
+ tests.
+ * The search addon (search.js) was slightly modified to make search
+ UI localizable (see patch below).
+
+Other than that, we don't have any Mozilla-specific patches applied to
+CodeMirror itself.
+
+## Addons
+
+To install a new CodeMirror 5 addon add it to the codemirror directory,
+jar.mn [4] file and editor.js [5]. Also, add it to the License section
+below.
+
+## License
+
+The following files in this directory and devtools/client/shared/sourceeditor/test/codemirror/
+are licensed according to the contents in the LICENSE file.
+
+## Localization patches
+
+diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/search/search.js b/devtools/client/shared/sourceeditor/codemirror/addon/search/search.js
+--- a/devtools/client/shared/sourceeditor/codemirror/addon/search/search.js
++++ b/devtools/client/shared/sourceeditor/codemirror/addon/search/search.js
+@@ -93,32 +93,47 @@
+ } else {
+ query = parseString(query)
+ }
+ if (typeof query == "string" ? query == "" : query.test(""))
+ query = /x^/;
+ return query;
+ }
+
+- var queryDialog =
+- '<span class="CodeMirror-search-label">Search:</span> <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">(Use /re/ syntax for regexp search)</span>';
++ var queryDialog;
+
+ function startSearch(cm, state, query) {
+ state.queryText = query;
+ state.query = parseQuery(query);
+ cm.removeOverlay(state.overlay, queryCaseInsensitive(state.query));
+ state.overlay = searchOverlay(state.query, queryCaseInsensitive(state.query));
+ cm.addOverlay(state.overlay);
+ if (cm.showMatchesOnScrollbar) {
+ if (state.annotate) { state.annotate.clear(); state.annotate = null; }
+ state.annotate = cm.showMatchesOnScrollbar(state.query, queryCaseInsensitive(state.query));
+ }
+ }
+
+ function doSearch(cm, rev, persistent, immediate) {
++ if (!queryDialog) {
++ let doc = cm.getWrapperElement().ownerDocument;
++ let inp = doc.createElement("input");
++
++ inp.type = "search";
++ inp.placeholder = cm.l10n("findCmd.promptMessage");
++ inp.style.marginInlineStart = "1em";
++ inp.style.marginInlineEnd = "1em";
++ inp.style.flexGrow = "1";
++ inp.addEventListener("focus", () => inp.select());
++
++ queryDialog = doc.createElement("div");
++ queryDialog.appendChild(inp);
++ queryDialog.style.display = "flex";
++ }
++
+ var state = getSearchState(cm);
+ if (state.query) return findNext(cm, rev);
+ var q = cm.getSelection() || state.lastQuery;
+ if (q instanceof RegExp && q.source == "x^") q = null
+ if (persistent && cm.openDialog) {
+ var hiding = null
+ var searchNext = function(query, event) {
+ CodeMirror.e_stop(event);
+@@ -181,56 +196,110 @@
+ var state = getSearchState(cm);
+ state.lastQuery = state.query;
+ if (!state.query) return;
+ state.query = state.queryText = null;
+ cm.removeOverlay(state.overlay);
+ if (state.annotate) { state.annotate.clear(); state.annotate = null; }
+ });}
+
+- var replaceQueryDialog =
+- ' <input type="text" style="width: 10em" class="CodeMirror-search-field"/> <span style="color: #888" class="CodeMirror-search-hint">(Use /re/ syntax for regexp search)</span>';
+- var replacementQueryDialog = '<span class="CodeMirror-search-label">With:</span> <input type="text" style="width: 10em" class="CodeMirror-search-field"/>';
+- var doReplaceConfirm = '<span class="CodeMirror-search-label">Replace?</span> <button>Yes</button> <button>No</button> <button>All</button> <button>Stop</button>';
+-
+ function replaceAll(cm, query, text) {
+ cm.operation(function() {
+ for (var cursor = getSearchCursor(cm, query); cursor.findNext();) {
+ if (typeof query != "string") {
+ var match = cm.getRange(cursor.from(), cursor.to()).match(query);
+ cursor.replace(text.replace(/\$(\d)/g, function(_, i) {return match[i];}));
+ } else cursor.replace(text);
+ }
+ });
+ }
+
+ function replace(cm, all) {
+ if (cm.getOption("readOnly")) return;
+ var query = cm.getSelection() || getSearchState(cm).lastQuery;
+- var dialogText = '<span class="CodeMirror-search-label">' + (all ? 'Replace all:' : 'Replace:') + '</span>';
+- dialog(cm, dialogText + replaceQueryDialog, dialogText, query, function(query) {
++
++ let doc = cm.getWrapperElement().ownerDocument;
++
++ // `searchLabel` is used as part of `replaceQueryFragment` and as a separate
++ // argument by itself, so it should be cloned.
++ let searchLabel = doc.createElement("span");
++ searchLabel.classList.add("CodeMirror-search-label");
++ searchLabel.textContent = all ? "Replace all:" : "Replace:";
++
++ let replaceQueryFragment = doc.createDocumentFragment();
++ replaceQueryFragment.appendChild(searchLabel.cloneNode(true));
++
++ let searchField = doc.createElement("input");
++ searchField.setAttribute("type", "text");
++ searchField.setAttribute("style", "width: 10em");
++ searchField.classList.add("CodeMirror-search-field");
++ replaceQueryFragment.appendChild(searchField);
++
++ let searchHint = doc.createElement("span");
++ searchHint.setAttribute("style", "color: #888");
++ searchHint.classList.add("CodeMirror-search-hint");
++ searchHint.textContent = "(Use /re/ syntax for regexp search)";
++ replaceQueryFragment.appendChild(searchHint);
++
++ dialog(cm, replaceQueryFragment, searchLabel, query, function(query) {
+ if (!query) return;
+ query = parseQuery(query);
+- dialog(cm, replacementQueryDialog, "Replace with:", "", function(text) {
++
++ let replacementQueryFragment = doc.createDocumentFragment();
++
++ let replaceWithLabel = searchLabel.cloneNode(false);
++ replaceWithLabel.textContent = "With:";
++ replacementQueryFragment.appendChild(replaceWithLabel);
++
++ let replaceField = doc.createElement("input");
++ replaceField.setAttribute("type", "text");
++ replaceField.setAttribute("style", "width: 10em");
++ replaceField.classList.add("CodeMirror-search-field");
++ replacementQueryFragment.appendChild(replaceField);
++
++ dialog(cm, replacementQueryFragment, "Replace with:", "", function(text) {
+ text = parseString(text)
+ if (all) {
+ replaceAll(cm, query, text)
+ } else {
+ clearSearch(cm);
+ var cursor = getSearchCursor(cm, query, cm.getCursor("from"));
+ var advance = function() {
+ var start = cursor.from(), match;
+ if (!(match = cursor.findNext())) {
+ cursor = getSearchCursor(cm, query);
+ if (!(match = cursor.findNext()) ||
+ (start && cursor.from().line == start.line && cursor.from().ch == start.ch)) return;
+ }
+ cm.setSelection(cursor.from(), cursor.to());
+- cm.scrollIntoView({from: cursor.from(), to: cursor.to()});
+- confirmDialog(cm, doReplaceConfirm, "Replace?",
++ cm.scrollIntoView({ from: cursor.from(), to: cursor.to() });
++
++ let replaceConfirmFragment = doc.createDocumentFragment();
++
++ let replaceConfirmLabel = searchLabel.cloneNode(false);
++ replaceConfirmLabel.textContent = "Replace?";
++ replaceConfirmFragment.appendChild(replaceConfirmLabel);
++
++ let yesButton = doc.createElement("button");
++ yesButton.textContent = "Yes";
++ replaceConfirmFragment.appendChild(yesButton);
++
++ let noButton = doc.createElement("button");
++ noButton.textContent = "No";
++ replaceConfirmFragment.appendChild(noButton);
++
++ let allButton = doc.createElement("button");
++ allButton.textContent = "All";
++ replaceConfirmFragment.appendChild(allButton);
++
++ let stopButton = doc.createElement("button");
++ stopButton.textContent = "Stop";
++ replaceConfirmFragment.appendChild(stopButton);
++
++ confirmDialog(cm, replaceConfirmFragment, "Replace?",
+ [function() {doReplace(match);}, advance,
+ function() {replaceAll(cm, query, text)}]);
+ };
+ var doReplace = function(match) {
+ cursor.replace(typeof query == "string" ? text :
+ text.replace(/\$(\d)/g, function(_, i) {return match[i];}));
+ advance();
+ };
+
+# Footnotes
+
+[1] http://codemirror.net
+[2] devtools/client/shared/sourceeditor/codemirror
+[3] devtools/client/shared/sourceeditor/test/browser_codemirror.js
+[4] devtools/client/jar.mn
+[5] devtools/client/shared/sourceeditor/editor.js
diff --git a/devtools/client/shared/sourceeditor/autocomplete.js b/devtools/client/shared/sourceeditor/autocomplete.js
new file mode 100644
index 0000000000..555bcf581c
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/autocomplete.js
@@ -0,0 +1,358 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+const AutocompletePopup = require("resource://devtools/client/shared/autocomplete-popup.js");
+
+loader.lazyRequireGetter(
+ this,
+ "KeyCodes",
+ "resource://devtools/client/shared/keycodes.js",
+ true
+);
+loader.lazyRequireGetter(
+ this,
+ "CSSCompleter",
+ "resource://devtools/client/shared/sourceeditor/css-autocompleter.js"
+);
+
+const autocompleteMap = new WeakMap();
+
+/**
+ * Prepares an editor instance for autocompletion.
+ */
+function initializeAutoCompletion(ctx, options = {}) {
+ const { cm, ed, Editor } = ctx;
+ if (autocompleteMap.has(ed)) {
+ return;
+ }
+
+ const win = ed.container.contentWindow.wrappedJSObject;
+ const { CodeMirror } = win;
+
+ let completer = null;
+ const autocompleteKey =
+ "Ctrl-" + Editor.keyFor("autocompletion", { noaccel: true });
+ if (ed.config.mode == Editor.modes.css) {
+ completer = new CSSCompleter({
+ walker: options.walker,
+ cssProperties: options.cssProperties,
+ });
+ }
+
+ function insertSelectedPopupItem() {
+ const autocompleteState = autocompleteMap.get(ed);
+ if (!popup || !popup.isOpen || !autocompleteState) {
+ return false;
+ }
+
+ if (!autocompleteState.suggestionInsertedOnce && popup.selectedItem) {
+ autocompleteMap.get(ed).insertingSuggestion = true;
+ insertPopupItem(ed, popup.selectedItem);
+ }
+
+ popup.once("popup-closed", () => {
+ // This event is used in tests.
+ ed.emit("popup-hidden");
+ });
+ popup.hidePopup();
+ return true;
+ }
+
+ // Give each popup a new name to avoid sharing the elements.
+
+ let popup = new AutocompletePopup(win.parent.document, {
+ position: "bottom",
+ autoSelect: true,
+ onClick: insertSelectedPopupItem,
+ });
+
+ const cycle = reverse => {
+ if (popup?.isOpen) {
+ // eslint-disable-next-line mozilla/no-compare-against-boolean-literals
+ cycleSuggestions(ed, reverse == true);
+ return null;
+ }
+
+ return CodeMirror.Pass;
+ };
+
+ let keyMap = {
+ Tab: cycle,
+ Down: cycle,
+ "Shift-Tab": cycle.bind(null, true),
+ Up: cycle.bind(null, true),
+ Enter: () => {
+ const wasHandled = insertSelectedPopupItem();
+ return wasHandled ? true : CodeMirror.Pass;
+ },
+ };
+
+ const autoCompleteCallback = autoComplete.bind(null, ctx);
+ const keypressCallback = onEditorKeypress.bind(null, ctx);
+ keyMap[autocompleteKey] = autoCompleteCallback;
+ cm.addKeyMap(keyMap);
+
+ cm.on("keydown", keypressCallback);
+ ed.on("change", autoCompleteCallback);
+ ed.on("destroy", destroy);
+
+ function destroy() {
+ ed.off("destroy", destroy);
+ cm.off("keydown", keypressCallback);
+ ed.off("change", autoCompleteCallback);
+ cm.removeKeyMap(keyMap);
+ popup.destroy();
+ keyMap = popup = completer = null;
+ autocompleteMap.delete(ed);
+ }
+
+ autocompleteMap.set(ed, {
+ popup,
+ completer,
+ keyMap,
+ destroy,
+ insertingSuggestion: false,
+ suggestionInsertedOnce: false,
+ });
+}
+
+/**
+ * Destroy autocompletion on an editor instance.
+ */
+function destroyAutoCompletion(ctx) {
+ const { ed } = ctx;
+ if (!autocompleteMap.has(ed)) {
+ return;
+ }
+
+ const { destroy } = autocompleteMap.get(ed);
+ destroy();
+}
+
+/**
+ * Provides suggestions to autocomplete the current token/word being typed.
+ */
+function autoComplete({ ed, cm }) {
+ const autocompleteOpts = autocompleteMap.get(ed);
+ const { completer, popup } = autocompleteOpts;
+ if (
+ !completer ||
+ autocompleteOpts.insertingSuggestion ||
+ autocompleteOpts.doNotAutocomplete
+ ) {
+ autocompleteOpts.insertingSuggestion = false;
+ return;
+ }
+ const cur = ed.getCursor();
+ completer
+ .complete(cm.getRange({ line: 0, ch: 0 }, cur), cur)
+ .then(suggestions => {
+ if (
+ !suggestions ||
+ !suggestions.length ||
+ suggestions[0].preLabel == null
+ ) {
+ autocompleteOpts.suggestionInsertedOnce = false;
+ popup.once("popup-closed", () => {
+ // This event is used in tests.
+ ed.emit("after-suggest");
+ });
+ popup.hidePopup();
+ return;
+ }
+ // The cursor is at the end of the currently entered part of the token,
+ // like "backgr|" but we need to open the popup at the beginning of the
+ // character "b". Thus we need to calculate the width of the entered part
+ // of the token ("backgr" here).
+
+ const cursorElement =
+ cm.display.cursorDiv.querySelector(".CodeMirror-cursor");
+ const left = suggestions[0].preLabel.length * cm.defaultCharWidth();
+ popup.hidePopup();
+ popup.setItems(suggestions);
+
+ popup.once("popup-opened", () => {
+ // This event is used in tests.
+ ed.emit("after-suggest");
+ });
+ popup.openPopup(cursorElement, -1 * left, 0);
+ autocompleteOpts.suggestionInsertedOnce = false;
+ })
+ .catch(console.error);
+}
+
+/**
+ * Inserts a popup item into the current cursor location
+ * in the editor.
+ */
+function insertPopupItem(ed, popupItem) {
+ const { preLabel, text } = popupItem;
+ const cur = ed.getCursor();
+ const textBeforeCursor = ed.getText(cur.line).substring(0, cur.ch);
+ const backwardsTextBeforeCursor = textBeforeCursor
+ .split("")
+ .reverse()
+ .join("");
+ const backwardsPreLabel = preLabel.split("").reverse().join("");
+
+ // If there is additional text in the preLabel vs the line, then
+ // just insert the entire autocomplete text. An example:
+ // if you type 'a' and select '#about' from the autocomplete menu,
+ // then the final text needs to the end up as '#about'.
+ if (backwardsPreLabel.indexOf(backwardsTextBeforeCursor) === 0) {
+ ed.replaceText(text, { line: cur.line, ch: 0 }, cur);
+ } else {
+ ed.replaceText(text.slice(preLabel.length), cur, cur);
+ }
+}
+
+/**
+ * Cycles through provided suggestions by the popup in a top to bottom manner
+ * when `reverse` is not true. Opposite otherwise.
+ */
+function cycleSuggestions(ed, reverse) {
+ const autocompleteOpts = autocompleteMap.get(ed);
+ const { popup } = autocompleteOpts;
+ const cur = ed.getCursor();
+ autocompleteOpts.insertingSuggestion = true;
+ if (!autocompleteOpts.suggestionInsertedOnce) {
+ autocompleteOpts.suggestionInsertedOnce = true;
+ let firstItem;
+ if (reverse) {
+ firstItem = popup.getItemAtIndex(popup.itemCount - 1);
+ popup.selectPreviousItem();
+ } else {
+ firstItem = popup.getItemAtIndex(0);
+ if (firstItem.label == firstItem.preLabel && popup.itemCount > 1) {
+ firstItem = popup.getItemAtIndex(1);
+ popup.selectNextItem();
+ }
+ }
+ if (popup.itemCount == 1) {
+ popup.hidePopup();
+ }
+ insertPopupItem(ed, firstItem);
+ } else {
+ const fromCur = {
+ line: cur.line,
+ ch: cur.ch - popup.selectedItem.text.length,
+ };
+ if (reverse) {
+ popup.selectPreviousItem();
+ } else {
+ popup.selectNextItem();
+ }
+ ed.replaceText(popup.selectedItem.text, fromCur, cur);
+ }
+ // This event is used in tests.
+ ed.emit("suggestion-entered");
+}
+
+/**
+ * onkeydown handler for the editor instance to prevent autocompleting on some
+ * keypresses.
+ */
+function onEditorKeypress({ ed, Editor }, cm, event) {
+ const autocompleteOpts = autocompleteMap.get(ed);
+
+ // Do not try to autocomplete with multiple selections.
+ if (ed.hasMultipleSelections()) {
+ autocompleteOpts.doNotAutocomplete = true;
+ autocompleteOpts.popup.hidePopup();
+ return;
+ }
+
+ if (
+ (event.ctrlKey || event.metaKey) &&
+ event.keyCode == KeyCodes.DOM_VK_SPACE
+ ) {
+ // When Ctrl/Cmd + Space is pressed, two simultaneous keypresses are emitted
+ // first one for just the Ctrl/Cmd and second one for combo. The first one
+ // leave the autocompleteOpts.doNotAutocomplete as true, so we have to make
+ // it false
+ autocompleteOpts.doNotAutocomplete = false;
+ return;
+ }
+
+ if (event.ctrlKey || event.metaKey || event.altKey) {
+ autocompleteOpts.doNotAutocomplete = true;
+ autocompleteOpts.popup.hidePopup();
+ return;
+ }
+
+ switch (event.keyCode) {
+ case KeyCodes.DOM_VK_RETURN:
+ autocompleteOpts.doNotAutocomplete = true;
+ break;
+ case KeyCodes.DOM_VK_ESCAPE:
+ if (autocompleteOpts.popup.isOpen) {
+ // Prevent the Console input to open, but still remove the autocomplete popup.
+ autocompleteOpts.doNotAutocomplete = true;
+ autocompleteOpts.popup.hidePopup();
+ event.preventDefault();
+ }
+ break;
+ case KeyCodes.DOM_VK_LEFT:
+ case KeyCodes.DOM_VK_RIGHT:
+ case KeyCodes.DOM_VK_HOME:
+ case KeyCodes.DOM_VK_END:
+ autocompleteOpts.doNotAutocomplete = true;
+ autocompleteOpts.popup.hidePopup();
+ break;
+ case KeyCodes.DOM_VK_BACK_SPACE:
+ case KeyCodes.DOM_VK_DELETE:
+ if (ed.config.mode == Editor.modes.css) {
+ autocompleteOpts.completer.invalidateCache(ed.getCursor().line);
+ }
+ autocompleteOpts.doNotAutocomplete = true;
+ autocompleteOpts.popup.hidePopup();
+ break;
+ default:
+ autocompleteOpts.doNotAutocomplete = false;
+ }
+}
+
+/**
+ * Returns the private popup. This method is used by tests to test the feature.
+ */
+function getPopup({ ed }) {
+ if (autocompleteMap.has(ed)) {
+ return autocompleteMap.get(ed).popup;
+ }
+
+ return null;
+}
+
+/**
+ * Returns contextual information about the token covered by the caret if the
+ * implementation of completer supports it.
+ */
+function getInfoAt({ ed }, caret) {
+ if (autocompleteMap.has(ed)) {
+ const completer = autocompleteMap.get(ed).completer;
+ if (completer?.getInfoAt) {
+ return completer.getInfoAt(ed.getText(), caret);
+ }
+ }
+
+ return null;
+}
+
+/**
+ * Returns whether autocompletion is enabled for this editor.
+ * Used for testing
+ */
+function isAutocompletionEnabled({ ed }) {
+ return autocompleteMap.has(ed);
+}
+
+// Export functions
+
+module.exports.initializeAutoCompletion = initializeAutoCompletion;
+module.exports.destroyAutoCompletion = destroyAutoCompletion;
+module.exports.getAutocompletionPopup = getPopup;
+module.exports.getInfoAt = getInfoAt;
+module.exports.isAutocompletionEnabled = isAutocompletionEnabled;
diff --git a/devtools/client/shared/sourceeditor/codemirror/LICENSE b/devtools/client/shared/sourceeditor/codemirror/LICENSE
new file mode 100644
index 0000000000..4db615dd23
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/LICENSE
@@ -0,0 +1,23 @@
+Copyright (C) 2015 by Marijn Haverbeke <marijnh@gmail.com> and others
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in
+all copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+THE SOFTWARE.
+
+Please note that some subdirectories of the CodeMirror distribution
+include their own LICENSE files, and are released under different
+licences.
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/accessibleTextarea.js b/devtools/client/shared/sourceeditor/codemirror/addon/accessibleTextarea.js
new file mode 100644
index 0000000000..6119ca0818
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/accessibleTextarea.js
@@ -0,0 +1,146 @@
+/*
+ * Copyright (C) 2012 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ * * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ * * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ * * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+(function(mod) {
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+})(function(CodeMirror) {
+ // CodeMirror uses an offscreen <textarea> to detect input.
+ // Due to inconsistencies in the many browsers it supports, it simplifies things by
+ // regularly checking if something is in the textarea, adding those characters to the
+ // document, and then clearing the textarea.
+ // This breaks assistive technology that wants to read from CodeMirror, because the
+ // <textarea> that they interact with is constantly empty.
+ // Because we target up-to-date Firefox, we can guarantee consistent input events.
+ // This lets us leave the current line from the editor in our <textarea>.
+ // CodeMirror still expects a mostly empty <textarea>, so we pass CodeMirror a fake
+ // <textarea> that only contains the users input.
+ CodeMirror.inputStyles.accessibleTextArea = class extends CodeMirror.inputStyles.textarea {
+ /**
+ * @override
+ * @param {!Object} display
+ */
+ init(display) {
+ super.init(display);
+ this.textarea.addEventListener("compositionstart",
+ this._onCompositionStart.bind(this));
+ }
+
+ _onCompositionStart() {
+ if (this.textarea.selectionEnd === this.textarea.value.length) {
+ return;
+ }
+
+ // CodeMirror always expects the caret to be at the end of the textarea
+ // When in IME composition mode, clip the textarea to how CodeMirror expects it,
+ // and then let CodeMirror do its thing.
+ this.textarea.value = this.textarea.value.substring(0, this.textarea.selectionEnd);
+ const length = this.textarea.value.length;
+ this.textarea.setSelectionRange(length, length);
+ this.prevInput = this.textarea.value;
+ }
+
+ /**
+ * @override
+ * @param {Boolean} typing
+ */
+ reset(typing) {
+ if (
+ typing ||
+ this.contextMenuPending ||
+ this.composing ||
+ this.cm.somethingSelected()
+ ) {
+ super.reset(typing);
+ return;
+ }
+
+ // When navigating around the document, keep the current visual line in the textarea.
+ const cursor = this.cm.getCursor();
+ let start, end;
+ if (this.cm.options.lineWrapping) {
+ // To get the visual line, compute the leftmost and rightmost character positions.
+ const top = this.cm.charCoords(cursor, "page").top;
+ start = this.cm.coordsChar({left: -Infinity, top});
+ end = this.cm.coordsChar({left: Infinity, top});
+ } else {
+ // Limit the line to 1000 characters to prevent lag.
+ const offset = Math.floor(cursor.ch / 1000) * 1000;
+ start = {ch: offset, line: cursor.line};
+ end = {ch: offset + 1000, line: cursor.line};
+ }
+
+ this.textarea.value = this.cm.getRange(start, end);
+ const caretPosition = cursor.ch - start.ch;
+ this.textarea.setSelectionRange(caretPosition, caretPosition);
+ this.prevInput = this.textarea.value;
+ }
+
+ /**
+ * @override
+ * @return {boolean}
+ */
+ poll() {
+ if (this.contextMenuPending || this.composing) {
+ return super.poll();
+ }
+
+ const text = this.textarea.value;
+ let start = 0;
+ const length = Math.min(this.prevInput.length, text.length);
+
+ while (start < length && this.prevInput[start] === text[start]) {
+ ++start;
+ }
+
+ let end = 0;
+
+ while (
+ end < length - start &&
+ this.prevInput[this.prevInput.length - end - 1] === text[text.length - end - 1]
+ ) {
+ ++end;
+ }
+
+ // CodeMirror expects the user to be typing into a blank <textarea>.
+ // Pass a fake textarea into super.poll that only contains the users input.
+ const placeholder = this.textarea;
+ this.textarea = document.createElement("textarea");
+ this.textarea.value = text.substring(start, text.length - end);
+ this.textarea.setSelectionRange(
+ placeholder.selectionStart - start,
+ placeholder.selectionEnd - start
+ );
+ this.prevInput = "";
+ const result = super.poll();
+ this.prevInput = text;
+ this.textarea = placeholder;
+ return result;
+ }
+ };
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/comment/comment.js b/devtools/client/shared/sourceeditor/codemirror/addon/comment/comment.js
new file mode 100644
index 0000000000..3a9dfc2f4e
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/comment/comment.js
@@ -0,0 +1,209 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ var noOptions = {};
+ var nonWS = /[^\s\u00a0]/;
+ var Pos = CodeMirror.Pos;
+
+ function firstNonWS(str) {
+ var found = str.search(nonWS);
+ return found == -1 ? 0 : found;
+ }
+
+ CodeMirror.commands.toggleComment = function(cm) {
+ cm.toggleComment();
+ };
+
+ CodeMirror.defineExtension("toggleComment", function(options) {
+ if (!options) options = noOptions;
+ var cm = this;
+ var minLine = Infinity, ranges = this.listSelections(), mode = null;
+ for (var i = ranges.length - 1; i >= 0; i--) {
+ var from = ranges[i].from(), to = ranges[i].to();
+ if (from.line >= minLine) continue;
+ if (to.line >= minLine) to = Pos(minLine, 0);
+ minLine = from.line;
+ if (mode == null) {
+ if (cm.uncomment(from, to, options)) mode = "un";
+ else { cm.lineComment(from, to, options); mode = "line"; }
+ } else if (mode == "un") {
+ cm.uncomment(from, to, options);
+ } else {
+ cm.lineComment(from, to, options);
+ }
+ }
+ });
+
+ // Rough heuristic to try and detect lines that are part of multi-line string
+ function probablyInsideString(cm, pos, line) {
+ return /\bstring\b/.test(cm.getTokenTypeAt(Pos(pos.line, 0))) && !/^[\'\"\`]/.test(line)
+ }
+
+ function getMode(cm, pos) {
+ var mode = cm.getMode()
+ return mode.useInnerComments === false || !mode.innerMode ? mode : cm.getModeAt(pos)
+ }
+
+ CodeMirror.defineExtension("lineComment", function(from, to, options) {
+ if (!options) options = noOptions;
+ var self = this, mode = getMode(self, from);
+ var firstLine = self.getLine(from.line);
+ if (firstLine == null || probablyInsideString(self, from, firstLine)) return;
+
+ var commentString = options.lineComment || mode.lineComment;
+ if (!commentString) {
+ if (options.blockCommentStart || mode.blockCommentStart) {
+ options.fullLines = true;
+ self.blockComment(from, to, options);
+ }
+ return;
+ }
+
+ var end = Math.min(to.ch != 0 || to.line == from.line ? to.line + 1 : to.line, self.lastLine() + 1);
+ var pad = options.padding == null ? " " : options.padding;
+ var blankLines = options.commentBlankLines || from.line == to.line;
+
+ self.operation(function() {
+ if (options.indent) {
+ var baseString = null;
+ for (var i = from.line; i < end; ++i) {
+ var line = self.getLine(i);
+ var whitespace = line.slice(0, firstNonWS(line));
+ if (baseString == null || baseString.length > whitespace.length) {
+ baseString = whitespace;
+ }
+ }
+ for (var i = from.line; i < end; ++i) {
+ var line = self.getLine(i), cut = baseString.length;
+ if (!blankLines && !nonWS.test(line)) continue;
+ if (line.slice(0, cut) != baseString) cut = firstNonWS(line);
+ self.replaceRange(baseString + commentString + pad, Pos(i, 0), Pos(i, cut));
+ }
+ } else {
+ for (var i = from.line; i < end; ++i) {
+ if (blankLines || nonWS.test(self.getLine(i)))
+ self.replaceRange(commentString + pad, Pos(i, 0));
+ }
+ }
+ });
+ });
+
+ CodeMirror.defineExtension("blockComment", function(from, to, options) {
+ if (!options) options = noOptions;
+ var self = this, mode = getMode(self, from);
+ var startString = options.blockCommentStart || mode.blockCommentStart;
+ var endString = options.blockCommentEnd || mode.blockCommentEnd;
+ if (!startString || !endString) {
+ if ((options.lineComment || mode.lineComment) && options.fullLines != false)
+ self.lineComment(from, to, options);
+ return;
+ }
+ if (/\bcomment\b/.test(self.getTokenTypeAt(Pos(from.line, 0)))) return
+
+ var end = Math.min(to.line, self.lastLine());
+ if (end != from.line && to.ch == 0 && nonWS.test(self.getLine(end))) --end;
+
+ var pad = options.padding == null ? " " : options.padding;
+ if (from.line > end) return;
+
+ self.operation(function() {
+ if (options.fullLines != false) {
+ var lastLineHasText = nonWS.test(self.getLine(end));
+ self.replaceRange(pad + endString, Pos(end));
+ self.replaceRange(startString + pad, Pos(from.line, 0));
+ var lead = options.blockCommentLead || mode.blockCommentLead;
+ if (lead != null) for (var i = from.line + 1; i <= end; ++i)
+ if (i != end || lastLineHasText)
+ self.replaceRange(lead + pad, Pos(i, 0));
+ } else {
+ self.replaceRange(endString, to);
+ self.replaceRange(startString, from);
+ }
+ });
+ });
+
+ CodeMirror.defineExtension("uncomment", function(from, to, options) {
+ if (!options) options = noOptions;
+ var self = this, mode = getMode(self, from);
+ var end = Math.min(to.ch != 0 || to.line == from.line ? to.line : to.line - 1, self.lastLine()), start = Math.min(from.line, end);
+
+ // Try finding line comments
+ var lineString = options.lineComment || mode.lineComment, lines = [];
+ var pad = options.padding == null ? " " : options.padding, didSomething;
+ lineComment: {
+ if (!lineString) break lineComment;
+ for (var i = start; i <= end; ++i) {
+ var line = self.getLine(i);
+ var found = line.indexOf(lineString);
+ if (found > -1 && !/comment/.test(self.getTokenTypeAt(Pos(i, found + 1)))) found = -1;
+ if (found == -1 && nonWS.test(line)) break lineComment;
+ if (found > -1 && nonWS.test(line.slice(0, found))) break lineComment;
+ lines.push(line);
+ }
+ self.operation(function() {
+ for (var i = start; i <= end; ++i) {
+ var line = lines[i - start];
+ var pos = line.indexOf(lineString), endPos = pos + lineString.length;
+ if (pos < 0) continue;
+ if (line.slice(endPos, endPos + pad.length) == pad) endPos += pad.length;
+ didSomething = true;
+ self.replaceRange("", Pos(i, pos), Pos(i, endPos));
+ }
+ });
+ if (didSomething) return true;
+ }
+
+ // Try block comments
+ var startString = options.blockCommentStart || mode.blockCommentStart;
+ var endString = options.blockCommentEnd || mode.blockCommentEnd;
+ if (!startString || !endString) return false;
+ var lead = options.blockCommentLead || mode.blockCommentLead;
+ var startLine = self.getLine(start), open = startLine.indexOf(startString)
+ if (open == -1) return false
+ var endLine = end == start ? startLine : self.getLine(end)
+ var close = endLine.indexOf(endString, end == start ? open + startString.length : 0);
+ var insideStart = Pos(start, open + 1), insideEnd = Pos(end, close + 1)
+ if (close == -1 ||
+ !/comment/.test(self.getTokenTypeAt(insideStart)) ||
+ !/comment/.test(self.getTokenTypeAt(insideEnd)) ||
+ self.getRange(insideStart, insideEnd, "\n").indexOf(endString) > -1)
+ return false;
+
+ // Avoid killing block comments completely outside the selection.
+ // Positions of the last startString before the start of the selection, and the first endString after it.
+ var lastStart = startLine.lastIndexOf(startString, from.ch);
+ var firstEnd = lastStart == -1 ? -1 : startLine.slice(0, from.ch).indexOf(endString, lastStart + startString.length);
+ if (lastStart != -1 && firstEnd != -1 && firstEnd + endString.length != from.ch) return false;
+ // Positions of the first endString after the end of the selection, and the last startString before it.
+ firstEnd = endLine.indexOf(endString, to.ch);
+ var almostLastStart = endLine.slice(to.ch).lastIndexOf(startString, firstEnd - to.ch);
+ lastStart = (firstEnd == -1 || almostLastStart == -1) ? -1 : to.ch + almostLastStart;
+ if (firstEnd != -1 && lastStart != -1 && lastStart != to.ch) return false;
+
+ self.operation(function() {
+ self.replaceRange("", Pos(end, close - (pad && endLine.slice(close - pad.length, close) == pad ? pad.length : 0)),
+ Pos(end, close + endString.length));
+ var openEnd = open + startString.length;
+ if (pad && startLine.slice(openEnd, openEnd + pad.length) == pad) openEnd += pad.length;
+ self.replaceRange("", Pos(start, open), Pos(start, openEnd));
+ if (lead) for (var i = start + 1; i <= end; ++i) {
+ var line = self.getLine(i), found = line.indexOf(lead);
+ if (found == -1 || nonWS.test(line.slice(0, found))) continue;
+ var foundEnd = found + lead.length;
+ if (pad && line.slice(foundEnd, foundEnd + pad.length) == pad) foundEnd += pad.length;
+ self.replaceRange("", Pos(i, found), Pos(i, foundEnd));
+ }
+ });
+ return true;
+ });
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/comment/continuecomment.js b/devtools/client/shared/sourceeditor/codemirror/addon/comment/continuecomment.js
new file mode 100644
index 0000000000..2dda5e5d92
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/comment/continuecomment.js
@@ -0,0 +1,78 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ function continueComment(cm) {
+ if (cm.getOption("disableInput")) return CodeMirror.Pass;
+ var ranges = cm.listSelections(), mode, inserts = [];
+ for (var i = 0; i < ranges.length; i++) {
+ var pos = ranges[i].head
+ if (!/\bcomment\b/.test(cm.getTokenTypeAt(pos))) return CodeMirror.Pass;
+ var modeHere = cm.getModeAt(pos)
+ if (!mode) mode = modeHere;
+ else if (mode != modeHere) return CodeMirror.Pass;
+
+ var insert = null;
+ if (mode.blockCommentStart && mode.blockCommentContinue) {
+ var line = cm.getLine(pos.line).slice(0, pos.ch)
+ var end = line.lastIndexOf(mode.blockCommentEnd), found
+ if (end != -1 && end == pos.ch - mode.blockCommentEnd.length) {
+ // Comment ended, don't continue it
+ } else if ((found = line.lastIndexOf(mode.blockCommentStart)) > -1 && found > end) {
+ insert = line.slice(0, found)
+ if (/\S/.test(insert)) {
+ insert = ""
+ for (var j = 0; j < found; ++j) insert += " "
+ }
+ } else if ((found = line.indexOf(mode.blockCommentContinue)) > -1 && !/\S/.test(line.slice(0, found))) {
+ insert = line.slice(0, found)
+ }
+ if (insert != null) insert += mode.blockCommentContinue
+ }
+ if (insert == null && mode.lineComment && continueLineCommentEnabled(cm)) {
+ var line = cm.getLine(pos.line), found = line.indexOf(mode.lineComment);
+ if (found > -1) {
+ insert = line.slice(0, found);
+ if (/\S/.test(insert)) insert = null;
+ else insert += mode.lineComment + line.slice(found + mode.lineComment.length).match(/^\s*/)[0];
+ }
+ }
+ if (insert == null) return CodeMirror.Pass;
+ inserts[i] = "\n" + insert;
+ }
+
+ cm.operation(function() {
+ for (var i = ranges.length - 1; i >= 0; i--)
+ cm.replaceRange(inserts[i], ranges[i].from(), ranges[i].to(), "+insert");
+ });
+ }
+
+ function continueLineCommentEnabled(cm) {
+ var opt = cm.getOption("continueComments");
+ if (opt && typeof opt == "object")
+ return opt.continueLineComment !== false;
+ return true;
+ }
+
+ CodeMirror.defineOption("continueComments", null, function(cm, val, prev) {
+ if (prev && prev != CodeMirror.Init)
+ cm.removeKeyMap("continueComment");
+ if (val) {
+ var key = "Enter";
+ if (typeof val == "string")
+ key = val;
+ else if (typeof val == "object" && val.key)
+ key = val.key;
+ var map = {name: "continueComment"};
+ map[key] = continueComment;
+ cm.addKeyMap(map);
+ }
+ });
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/dialog/dialog.css b/devtools/client/shared/sourceeditor/codemirror/addon/dialog/dialog.css
new file mode 100644
index 0000000000..677c078387
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/dialog/dialog.css
@@ -0,0 +1,32 @@
+.CodeMirror-dialog {
+ position: absolute;
+ left: 0; right: 0;
+ background: inherit;
+ z-index: 15;
+ padding: .1em .8em;
+ overflow: hidden;
+ color: inherit;
+}
+
+.CodeMirror-dialog-top {
+ border-bottom: 1px solid #eee;
+ top: 0;
+}
+
+.CodeMirror-dialog-bottom {
+ border-top: 1px solid #eee;
+ bottom: 0;
+}
+
+.CodeMirror-dialog input {
+ border: none;
+ outline: none;
+ background: transparent;
+ width: 20em;
+ color: inherit;
+ font-family: monospace;
+}
+
+.CodeMirror-dialog button {
+ font-size: 70%;
+}
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/dialog/dialog.js b/devtools/client/shared/sourceeditor/codemirror/addon/dialog/dialog.js
new file mode 100644
index 0000000000..ac9bd333f0
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/dialog/dialog.js
@@ -0,0 +1,161 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+// Open simple dialogs on top of an editor. Relies on dialog.css.
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ function dialogDiv(cm, template, bottom) {
+ var wrap = cm.getWrapperElement();
+ var dialog;
+ dialog = wrap.appendChild(document.createElement("div"));
+ if (bottom)
+ dialog.className = "CodeMirror-dialog CodeMirror-dialog-bottom";
+ else
+ dialog.className = "CodeMirror-dialog CodeMirror-dialog-top";
+
+ if (typeof template == "string") {
+ dialog.innerHTML = template;
+ } else { // Assuming it's a detached DOM element.
+ dialog.appendChild(template);
+ }
+ CodeMirror.addClass(wrap, 'dialog-opened');
+ return dialog;
+ }
+
+ function closeNotification(cm, newVal) {
+ if (cm.state.currentNotificationClose)
+ cm.state.currentNotificationClose();
+ cm.state.currentNotificationClose = newVal;
+ }
+
+ CodeMirror.defineExtension("openDialog", function(template, callback, options) {
+ if (!options) options = {};
+
+ closeNotification(this, null);
+
+ var dialog = dialogDiv(this, template, options.bottom);
+ var closed = false, me = this;
+ function close(newVal) {
+ if (typeof newVal == 'string') {
+ inp.value = newVal;
+ } else {
+ if (closed) return;
+ closed = true;
+ CodeMirror.rmClass(dialog.parentNode, 'dialog-opened');
+ dialog.parentNode.removeChild(dialog);
+ me.focus();
+
+ if (options.onClose) options.onClose(dialog);
+ }
+ }
+
+ var inp = dialog.getElementsByTagName("input")[0], button;
+ if (inp) {
+ inp.focus();
+
+ if (options.value) {
+ inp.value = options.value;
+ if (options.selectValueOnOpen !== false) {
+ inp.select();
+ }
+ }
+
+ if (options.onInput)
+ CodeMirror.on(inp, "input", function(e) { options.onInput(e, inp.value, close);});
+ if (options.onKeyUp)
+ CodeMirror.on(inp, "keyup", function(e) {options.onKeyUp(e, inp.value, close);});
+
+ CodeMirror.on(inp, "keydown", function(e) {
+ if (options && options.onKeyDown && options.onKeyDown(e, inp.value, close)) { return; }
+ if (e.keyCode == 27 || (options.closeOnEnter !== false && e.keyCode == 13)) {
+ inp.blur();
+ CodeMirror.e_stop(e);
+ close();
+ }
+ if (e.keyCode == 13) callback(inp.value, e);
+ });
+
+ if (options.closeOnBlur !== false) CodeMirror.on(inp, "blur", close);
+ } else if (button = dialog.getElementsByTagName("button")[0]) {
+ CodeMirror.on(button, "click", function() {
+ close();
+ me.focus();
+ });
+
+ if (options.closeOnBlur !== false) CodeMirror.on(button, "blur", close);
+
+ button.focus();
+ }
+ return close;
+ });
+
+ CodeMirror.defineExtension("openConfirm", function(template, callbacks, options) {
+ closeNotification(this, null);
+ var dialog = dialogDiv(this, template, options && options.bottom);
+ var buttons = dialog.getElementsByTagName("button");
+ var closed = false, me = this, blurring = 1;
+ function close() {
+ if (closed) return;
+ closed = true;
+ CodeMirror.rmClass(dialog.parentNode, 'dialog-opened');
+ dialog.parentNode.removeChild(dialog);
+ me.focus();
+ }
+ buttons[0].focus();
+ for (var i = 0; i < buttons.length; ++i) {
+ var b = buttons[i];
+ (function(callback) {
+ CodeMirror.on(b, "click", function(e) {
+ CodeMirror.e_preventDefault(e);
+ close();
+ if (callback) callback(me);
+ });
+ })(callbacks[i]);
+ CodeMirror.on(b, "blur", function() {
+ --blurring;
+ setTimeout(function() { if (blurring <= 0) close(); }, 200);
+ });
+ CodeMirror.on(b, "focus", function() { ++blurring; });
+ }
+ });
+
+ /*
+ * openNotification
+ * Opens a notification, that can be closed with an optional timer
+ * (default 5000ms timer) and always closes on click.
+ *
+ * If a notification is opened while another is opened, it will close the
+ * currently opened one and open the new one immediately.
+ */
+ CodeMirror.defineExtension("openNotification", function(template, options) {
+ closeNotification(this, close);
+ var dialog = dialogDiv(this, template, options && options.bottom);
+ var closed = false, doneTimer;
+ var duration = options && typeof options.duration !== "undefined" ? options.duration : 5000;
+
+ function close() {
+ if (closed) return;
+ closed = true;
+ clearTimeout(doneTimer);
+ CodeMirror.rmClass(dialog.parentNode, 'dialog-opened');
+ dialog.parentNode.removeChild(dialog);
+ }
+
+ CodeMirror.on(dialog, 'click', function(e) {
+ CodeMirror.e_preventDefault(e);
+ close();
+ });
+
+ if (duration)
+ doneTimer = setTimeout(close, duration);
+
+ return close;
+ });
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/display/placeholder.js b/devtools/client/shared/sourceeditor/codemirror/addon/display/placeholder.js
new file mode 100644
index 0000000000..e3f95a49c4
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/display/placeholder.js
@@ -0,0 +1,63 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(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) {
+ CodeMirror.defineOption("placeholder", "", function(cm, val, old) {
+ var prev = old && old != CodeMirror.Init;
+ if (val && !prev) {
+ cm.on("blur", onBlur);
+ cm.on("change", onChange);
+ cm.on("swapDoc", onChange);
+ onChange(cm);
+ } else if (!val && prev) {
+ cm.off("blur", onBlur);
+ cm.off("change", onChange);
+ cm.off("swapDoc", onChange);
+ clearPlaceholder(cm);
+ var wrapper = cm.getWrapperElement();
+ wrapper.className = wrapper.className.replace(" CodeMirror-empty", "");
+ }
+
+ if (val && !cm.hasFocus()) onBlur(cm);
+ });
+
+ function clearPlaceholder(cm) {
+ if (cm.state.placeholder) {
+ cm.state.placeholder.parentNode.removeChild(cm.state.placeholder);
+ cm.state.placeholder = null;
+ }
+ }
+ function setPlaceholder(cm) {
+ clearPlaceholder(cm);
+ var elt = cm.state.placeholder = document.createElement("pre");
+ elt.style.cssText = "height: 0; overflow: visible";
+ elt.style.direction = cm.getOption("direction");
+ elt.className = "CodeMirror-placeholder CodeMirror-line-like";
+ var placeHolder = cm.getOption("placeholder")
+ if (typeof placeHolder == "string") placeHolder = document.createTextNode(placeHolder)
+ elt.appendChild(placeHolder)
+ cm.display.lineSpace.insertBefore(elt, cm.display.lineSpace.firstChild);
+ }
+
+ function onBlur(cm) {
+ if (isEmpty(cm)) setPlaceholder(cm);
+ }
+ function onChange(cm) {
+ var wrapper = cm.getWrapperElement(), empty = isEmpty(cm);
+ wrapper.className = wrapper.className.replace(" CodeMirror-empty", "") + (empty ? " CodeMirror-empty" : "");
+
+ if (empty) setPlaceholder(cm);
+ else clearPlaceholder(cm);
+ }
+
+ function isEmpty(cm) {
+ return (cm.lineCount() === 1) && (cm.getLine(0) === "");
+ }
+}); \ No newline at end of file
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/edit/closebrackets.js b/devtools/client/shared/sourceeditor/codemirror/addon/edit/closebrackets.js
new file mode 100644
index 0000000000..95c88bdf88
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/edit/closebrackets.js
@@ -0,0 +1,191 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ var defaults = {
+ pairs: "()[]{}''\"\"",
+ closeBefore: ")]}'\":;>",
+ triples: "",
+ explode: "[]{}"
+ };
+
+ var Pos = CodeMirror.Pos;
+
+ CodeMirror.defineOption("autoCloseBrackets", false, function(cm, val, old) {
+ if (old && old != CodeMirror.Init) {
+ cm.removeKeyMap(keyMap);
+ cm.state.closeBrackets = null;
+ }
+ if (val) {
+ ensureBound(getOption(val, "pairs"))
+ cm.state.closeBrackets = val;
+ cm.addKeyMap(keyMap);
+ }
+ });
+
+ function getOption(conf, name) {
+ if (name == "pairs" && typeof conf == "string") return conf;
+ if (typeof conf == "object" && conf[name] != null) return conf[name];
+ return defaults[name];
+ }
+
+ var keyMap = {Backspace: handleBackspace, Enter: handleEnter};
+ function ensureBound(chars) {
+ for (var i = 0; i < chars.length; i++) {
+ var ch = chars.charAt(i), key = "'" + ch + "'"
+ if (!keyMap[key]) keyMap[key] = handler(ch)
+ }
+ }
+ ensureBound(defaults.pairs + "`")
+
+ function handler(ch) {
+ return function(cm) { return handleChar(cm, ch); };
+ }
+
+ function getConfig(cm) {
+ var deflt = cm.state.closeBrackets;
+ if (!deflt || deflt.override) return deflt;
+ var mode = cm.getModeAt(cm.getCursor());
+ return mode.closeBrackets || deflt;
+ }
+
+ function handleBackspace(cm) {
+ var conf = getConfig(cm);
+ if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass;
+
+ var pairs = getOption(conf, "pairs");
+ var ranges = cm.listSelections();
+ for (var i = 0; i < ranges.length; i++) {
+ if (!ranges[i].empty()) return CodeMirror.Pass;
+ var around = charsAround(cm, ranges[i].head);
+ if (!around || pairs.indexOf(around) % 2 != 0) return CodeMirror.Pass;
+ }
+ for (var i = ranges.length - 1; i >= 0; i--) {
+ var cur = ranges[i].head;
+ cm.replaceRange("", Pos(cur.line, cur.ch - 1), Pos(cur.line, cur.ch + 1), "+delete");
+ }
+ }
+
+ function handleEnter(cm) {
+ var conf = getConfig(cm);
+ var explode = conf && getOption(conf, "explode");
+ if (!explode || cm.getOption("disableInput")) return CodeMirror.Pass;
+
+ var ranges = cm.listSelections();
+ for (var i = 0; i < ranges.length; i++) {
+ if (!ranges[i].empty()) return CodeMirror.Pass;
+ var around = charsAround(cm, ranges[i].head);
+ if (!around || explode.indexOf(around) % 2 != 0) return CodeMirror.Pass;
+ }
+ cm.operation(function() {
+ var linesep = cm.lineSeparator() || "\n";
+ cm.replaceSelection(linesep + linesep, null);
+ cm.execCommand("goCharLeft");
+ ranges = cm.listSelections();
+ for (var i = 0; i < ranges.length; i++) {
+ var line = ranges[i].head.line;
+ cm.indentLine(line, null, true);
+ cm.indentLine(line + 1, null, true);
+ }
+ });
+ }
+
+ function contractSelection(sel) {
+ var inverted = CodeMirror.cmpPos(sel.anchor, sel.head) > 0;
+ return {anchor: new Pos(sel.anchor.line, sel.anchor.ch + (inverted ? -1 : 1)),
+ head: new Pos(sel.head.line, sel.head.ch + (inverted ? 1 : -1))};
+ }
+
+ function handleChar(cm, ch) {
+ var conf = getConfig(cm);
+ if (!conf || cm.getOption("disableInput")) return CodeMirror.Pass;
+
+ var pairs = getOption(conf, "pairs");
+ var pos = pairs.indexOf(ch);
+ if (pos == -1) return CodeMirror.Pass;
+
+ var closeBefore = getOption(conf,"closeBefore");
+
+ var triples = getOption(conf, "triples");
+
+ var identical = pairs.charAt(pos + 1) == ch;
+ var ranges = cm.listSelections();
+ var opening = pos % 2 == 0;
+
+ var type;
+ for (var i = 0; i < ranges.length; i++) {
+ var range = ranges[i], cur = range.head, curType;
+ var next = cm.getRange(cur, Pos(cur.line, cur.ch + 1));
+ if (opening && !range.empty()) {
+ curType = "surround";
+ } else if ((identical || !opening) && next == ch) {
+ if (identical && stringStartsAfter(cm, cur))
+ curType = "both";
+ else if (triples.indexOf(ch) >= 0 && cm.getRange(cur, Pos(cur.line, cur.ch + 3)) == ch + ch + ch)
+ curType = "skipThree";
+ else
+ curType = "skip";
+ } else if (identical && cur.ch > 1 && triples.indexOf(ch) >= 0 &&
+ cm.getRange(Pos(cur.line, cur.ch - 2), cur) == ch + ch) {
+ if (cur.ch > 2 && /\bstring/.test(cm.getTokenTypeAt(Pos(cur.line, cur.ch - 2)))) return CodeMirror.Pass;
+ curType = "addFour";
+ } else if (identical) {
+ var prev = cur.ch == 0 ? " " : cm.getRange(Pos(cur.line, cur.ch - 1), cur)
+ if (!CodeMirror.isWordChar(next) && prev != ch && !CodeMirror.isWordChar(prev)) curType = "both";
+ else return CodeMirror.Pass;
+ } else if (opening && (next.length === 0 || /\s/.test(next) || closeBefore.indexOf(next) > -1)) {
+ curType = "both";
+ } else {
+ return CodeMirror.Pass;
+ }
+ if (!type) type = curType;
+ else if (type != curType) return CodeMirror.Pass;
+ }
+
+ var left = pos % 2 ? pairs.charAt(pos - 1) : ch;
+ var right = pos % 2 ? ch : pairs.charAt(pos + 1);
+ cm.operation(function() {
+ if (type == "skip") {
+ cm.execCommand("goCharRight");
+ } else if (type == "skipThree") {
+ for (var i = 0; i < 3; i++)
+ cm.execCommand("goCharRight");
+ } else if (type == "surround") {
+ var sels = cm.getSelections();
+ for (var i = 0; i < sels.length; i++)
+ sels[i] = left + sels[i] + right;
+ cm.replaceSelections(sels, "around");
+ sels = cm.listSelections().slice();
+ for (var i = 0; i < sels.length; i++)
+ sels[i] = contractSelection(sels[i]);
+ cm.setSelections(sels);
+ } else if (type == "both") {
+ cm.replaceSelection(left + right, null);
+ cm.triggerElectric(left + right);
+ cm.execCommand("goCharLeft");
+ } else if (type == "addFour") {
+ cm.replaceSelection(left + left + left + left, "before");
+ cm.execCommand("goCharRight");
+ }
+ });
+ }
+
+ function charsAround(cm, pos) {
+ var str = cm.getRange(Pos(pos.line, pos.ch - 1),
+ Pos(pos.line, pos.ch + 1));
+ return str.length == 2 ? str : null;
+ }
+
+ function stringStartsAfter(cm, pos) {
+ var token = cm.getTokenAt(Pos(pos.line, pos.ch + 1))
+ return /\bstring/.test(token.type) && token.start == pos.ch &&
+ (pos.ch == 0 || !/\bstring/.test(cm.getTokenTypeAt(pos)))
+ }
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/edit/closetag.js b/devtools/client/shared/sourceeditor/codemirror/addon/edit/closetag.js
new file mode 100644
index 0000000000..617cf71854
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/edit/closetag.js
@@ -0,0 +1,184 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+/**
+ * Tag-closer extension for CodeMirror.
+ *
+ * This extension adds an "autoCloseTags" option that can be set to
+ * either true to get the default behavior, or an object to further
+ * configure its behavior.
+ *
+ * These are supported options:
+ *
+ * `whenClosing` (default true)
+ * Whether to autoclose when the '/' of a closing tag is typed.
+ * `whenOpening` (default true)
+ * Whether to autoclose the tag when the final '>' of an opening
+ * tag is typed.
+ * `dontCloseTags` (default is empty tags for HTML, none for XML)
+ * An array of tag names that should not be autoclosed.
+ * `indentTags` (default is block tags for HTML, none for XML)
+ * An array of tag names that should, when opened, cause a
+ * blank line to be added inside the tag, and the blank line and
+ * closing line to be indented.
+ * `emptyTags` (default is none)
+ * An array of XML tag names that should be autoclosed with '/>'.
+ *
+ * See demos/closetag.html for a usage example.
+ */
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"), require("resource://devtools/client/shared/sourceeditor/codemirror/addon/fold/xml-fold.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror", "../fold/xml-fold"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ CodeMirror.defineOption("autoCloseTags", false, function(cm, val, old) {
+ if (old != CodeMirror.Init && old)
+ cm.removeKeyMap("autoCloseTags");
+ if (!val) return;
+ var map = {name: "autoCloseTags"};
+ if (typeof val != "object" || val.whenClosing)
+ map["'/'"] = function(cm) { return autoCloseSlash(cm); };
+ if (typeof val != "object" || val.whenOpening)
+ map["'>'"] = function(cm) { return autoCloseGT(cm); };
+ cm.addKeyMap(map);
+ });
+
+ var htmlDontClose = ["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param",
+ "source", "track", "wbr"];
+ var htmlIndent = ["applet", "blockquote", "body", "button", "div", "dl", "fieldset", "form", "frameset", "h1", "h2", "h3", "h4",
+ "h5", "h6", "head", "html", "iframe", "layer", "legend", "object", "ol", "p", "select", "table", "ul"];
+
+ function autoCloseGT(cm) {
+ if (cm.getOption("disableInput")) return CodeMirror.Pass;
+ var ranges = cm.listSelections(), replacements = [];
+ var opt = cm.getOption("autoCloseTags");
+ for (var i = 0; i < ranges.length; i++) {
+ if (!ranges[i].empty()) return CodeMirror.Pass;
+ var pos = ranges[i].head, tok = cm.getTokenAt(pos);
+ var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state;
+ var tagInfo = inner.mode.xmlCurrentTag && inner.mode.xmlCurrentTag(state)
+ var tagName = tagInfo && tagInfo.name
+ if (!tagName) return CodeMirror.Pass
+
+ var html = inner.mode.configuration == "html";
+ var dontCloseTags = (typeof opt == "object" && opt.dontCloseTags) || (html && htmlDontClose);
+ var indentTags = (typeof opt == "object" && opt.indentTags) || (html && htmlIndent);
+
+ if (tok.end > pos.ch) tagName = tagName.slice(0, tagName.length - tok.end + pos.ch);
+ var lowerTagName = tagName.toLowerCase();
+ // Don't process the '>' at the end of an end-tag or self-closing tag
+ if (!tagName ||
+ tok.type == "string" && (tok.end != pos.ch || !/[\"\']/.test(tok.string.charAt(tok.string.length - 1)) || tok.string.length == 1) ||
+ tok.type == "tag" && tagInfo.close ||
+ tok.string.indexOf("/") == (tok.string.length - 1) || // match something like <someTagName />
+ dontCloseTags && indexOf(dontCloseTags, lowerTagName) > -1 ||
+ closingTagExists(cm, inner.mode.xmlCurrentContext && inner.mode.xmlCurrentContext(state) || [], tagName, pos, true))
+ return CodeMirror.Pass;
+
+ var emptyTags = typeof opt == "object" && opt.emptyTags;
+ if (emptyTags && indexOf(emptyTags, tagName) > -1) {
+ replacements[i] = { text: "/>", newPos: CodeMirror.Pos(pos.line, pos.ch + 2) };
+ continue;
+ }
+
+ var indent = indentTags && indexOf(indentTags, lowerTagName) > -1;
+ replacements[i] = {indent: indent,
+ text: ">" + (indent ? "\n\n" : "") + "</" + tagName + ">",
+ newPos: indent ? CodeMirror.Pos(pos.line + 1, 0) : CodeMirror.Pos(pos.line, pos.ch + 1)};
+ }
+
+ var dontIndentOnAutoClose = (typeof opt == "object" && opt.dontIndentOnAutoClose);
+ for (var i = ranges.length - 1; i >= 0; i--) {
+ var info = replacements[i];
+ cm.replaceRange(info.text, ranges[i].head, ranges[i].anchor, "+insert");
+ var sel = cm.listSelections().slice(0);
+ sel[i] = {head: info.newPos, anchor: info.newPos};
+ cm.setSelections(sel);
+ if (!dontIndentOnAutoClose && info.indent) {
+ cm.indentLine(info.newPos.line, null, true);
+ cm.indentLine(info.newPos.line + 1, null, true);
+ }
+ }
+ }
+
+ function autoCloseCurrent(cm, typingSlash) {
+ var ranges = cm.listSelections(), replacements = [];
+ var head = typingSlash ? "/" : "</";
+ var opt = cm.getOption("autoCloseTags");
+ var dontIndentOnAutoClose = (typeof opt == "object" && opt.dontIndentOnSlash);
+ for (var i = 0; i < ranges.length; i++) {
+ if (!ranges[i].empty()) return CodeMirror.Pass;
+ var pos = ranges[i].head, tok = cm.getTokenAt(pos);
+ var inner = CodeMirror.innerMode(cm.getMode(), tok.state), state = inner.state;
+ if (typingSlash && (tok.type == "string" || tok.string.charAt(0) != "<" ||
+ tok.start != pos.ch - 1))
+ return CodeMirror.Pass;
+ // Kludge to get around the fact that we are not in XML mode
+ // when completing in JS/CSS snippet in htmlmixed mode. Does not
+ // work for other XML embedded languages (there is no general
+ // way to go from a mixed mode to its current XML state).
+ var replacement, mixed = inner.mode.name != "xml" && cm.getMode().name == "htmlmixed"
+ if (mixed && inner.mode.name == "javascript") {
+ replacement = head + "script";
+ } else if (mixed && inner.mode.name == "css") {
+ replacement = head + "style";
+ } else {
+ var context = inner.mode.xmlCurrentContext && inner.mode.xmlCurrentContext(state)
+ if (!context || (context.length && closingTagExists(cm, context, context[context.length - 1], pos)))
+ return CodeMirror.Pass;
+ replacement = head + context[context.length - 1]
+ }
+ if (cm.getLine(pos.line).charAt(tok.end) != ">") replacement += ">";
+ replacements[i] = replacement;
+ }
+ cm.replaceSelections(replacements);
+ ranges = cm.listSelections();
+ if (!dontIndentOnAutoClose) {
+ for (var i = 0; i < ranges.length; i++)
+ if (i == ranges.length - 1 || ranges[i].head.line < ranges[i + 1].head.line)
+ cm.indentLine(ranges[i].head.line);
+ }
+ }
+
+ function autoCloseSlash(cm) {
+ if (cm.getOption("disableInput")) return CodeMirror.Pass;
+ return autoCloseCurrent(cm, true);
+ }
+
+ CodeMirror.commands.closeTag = function(cm) { return autoCloseCurrent(cm); };
+
+ function indexOf(collection, elt) {
+ if (collection.indexOf) return collection.indexOf(elt);
+ for (var i = 0, e = collection.length; i < e; ++i)
+ if (collection[i] == elt) return i;
+ return -1;
+ }
+
+ // If xml-fold is loaded, we use its functionality to try and verify
+ // whether a given tag is actually unclosed.
+ function closingTagExists(cm, context, tagName, pos, newTag) {
+ if (!CodeMirror.scanForClosingTag) return false;
+ var end = Math.min(cm.lastLine() + 1, pos.line + 500);
+ var nextClose = CodeMirror.scanForClosingTag(cm, pos, null, end);
+ if (!nextClose || nextClose.tag != tagName) return false;
+ // If the immediate wrapping context contains onCx instances of
+ // the same tag, a closing tag only exists if there are at least
+ // that many closing tags of that type following.
+ var onCx = newTag ? 1 : 0
+ for (var i = context.length - 1; i >= 0; i--) {
+ if (context[i] == tagName) ++onCx
+ else break
+ }
+ pos = nextClose.to;
+ for (var i = 1; i < onCx; i++) {
+ var next = CodeMirror.scanForClosingTag(cm, pos, null, end);
+ if (!next || next.tag != tagName) return false;
+ pos = next.to;
+ }
+ return true;
+ }
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/edit/continuelist.js b/devtools/client/shared/sourceeditor/codemirror/addon/edit/continuelist.js
new file mode 100644
index 0000000000..222995f4d1
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/edit/continuelist.js
@@ -0,0 +1,99 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ var listRE = /^(\s*)(>[> ]*|[*+-] \[[x ]\]\s|[*+-]\s|(\d+)([.)]))(\s*)/,
+ emptyListRE = /^(\s*)(>[> ]*|[*+-] \[[x ]\]|[*+-]|(\d+)[.)])(\s*)$/,
+ unorderedListRE = /[*+-]\s/;
+
+ CodeMirror.commands.newlineAndIndentContinueMarkdownList = function(cm) {
+ if (cm.getOption("disableInput")) return CodeMirror.Pass;
+ var ranges = cm.listSelections(), replacements = [];
+ for (var i = 0; i < ranges.length; i++) {
+ var pos = ranges[i].head;
+
+ // If we're not in Markdown mode, fall back to normal newlineAndIndent
+ var eolState = cm.getStateAfter(pos.line);
+ var inner = CodeMirror.innerMode(cm.getMode(), eolState);
+ if (inner.mode.name !== "markdown") {
+ cm.execCommand("newlineAndIndent");
+ return;
+ } else {
+ eolState = inner.state;
+ }
+
+ var inList = eolState.list !== false;
+ var inQuote = eolState.quote !== 0;
+
+ var line = cm.getLine(pos.line), match = listRE.exec(line);
+ var cursorBeforeBullet = /^\s*$/.test(line.slice(0, pos.ch));
+ if (!ranges[i].empty() || (!inList && !inQuote) || !match || cursorBeforeBullet) {
+ cm.execCommand("newlineAndIndent");
+ return;
+ }
+ if (emptyListRE.test(line)) {
+ if (!/>\s*$/.test(line)) cm.replaceRange("", {
+ line: pos.line, ch: 0
+ }, {
+ line: pos.line, ch: pos.ch + 1
+ });
+ replacements[i] = "\n";
+ } else {
+ var indent = match[1], after = match[5];
+ var numbered = !(unorderedListRE.test(match[2]) || match[2].indexOf(">") >= 0);
+ var bullet = numbered ? (parseInt(match[3], 10) + 1) + match[4] : match[2].replace("x", " ");
+ replacements[i] = "\n" + indent + bullet + after;
+
+ if (numbered) incrementRemainingMarkdownListNumbers(cm, pos);
+ }
+ }
+
+ cm.replaceSelections(replacements);
+ };
+
+ // Auto-updating Markdown list numbers when a new item is added to the
+ // middle of a list
+ function incrementRemainingMarkdownListNumbers(cm, pos) {
+ var startLine = pos.line, lookAhead = 0, skipCount = 0;
+ var startItem = listRE.exec(cm.getLine(startLine)), startIndent = startItem[1];
+
+ do {
+ lookAhead += 1;
+ var nextLineNumber = startLine + lookAhead;
+ var nextLine = cm.getLine(nextLineNumber), nextItem = listRE.exec(nextLine);
+
+ if (nextItem) {
+ var nextIndent = nextItem[1];
+ var newNumber = (parseInt(startItem[3], 10) + lookAhead - skipCount);
+ var nextNumber = (parseInt(nextItem[3], 10)), itemNumber = nextNumber;
+
+ if (startIndent === nextIndent && !isNaN(nextNumber)) {
+ if (newNumber === nextNumber) itemNumber = nextNumber + 1;
+ if (newNumber > nextNumber) itemNumber = newNumber + 1;
+ cm.replaceRange(
+ nextLine.replace(listRE, nextIndent + itemNumber + nextItem[4] + nextItem[5]),
+ {
+ line: nextLineNumber, ch: 0
+ }, {
+ line: nextLineNumber, ch: nextLine.length
+ });
+ } else {
+ if (startIndent.length > nextIndent.length) return;
+ // This doesn't run if the next line immediatley indents, as it is
+ // not clear of the users intention (new indented item or same level)
+ if ((startIndent.length < nextIndent.length) && (lookAhead === 1)) return;
+ skipCount += 1;
+ }
+ }
+ } while (nextItem);
+ }
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/edit/matchbrackets.js b/devtools/client/shared/sourceeditor/codemirror/addon/edit/matchbrackets.js
new file mode 100644
index 0000000000..a688935672
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/edit/matchbrackets.js
@@ -0,0 +1,150 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ var ie_lt8 = /MSIE \d/.test(navigator.userAgent) &&
+ (document.documentMode == null || document.documentMode < 8);
+
+ var Pos = CodeMirror.Pos;
+
+ var matching = {"(": ")>", ")": "(<", "[": "]>", "]": "[<", "{": "}>", "}": "{<", "<": ">>", ">": "<<"};
+
+ function bracketRegex(config) {
+ return config && config.bracketRegex || /[(){}[\]]/
+ }
+
+ function findMatchingBracket(cm, where, config) {
+ var line = cm.getLineHandle(where.line), pos = where.ch - 1;
+ var afterCursor = config && config.afterCursor
+ if (afterCursor == null)
+ afterCursor = /(^| )cm-fat-cursor($| )/.test(cm.getWrapperElement().className)
+ var re = bracketRegex(config)
+
+ // A cursor is defined as between two characters, but in in vim command mode
+ // (i.e. not insert mode), the cursor is visually represented as a
+ // highlighted box on top of the 2nd character. Otherwise, we allow matches
+ // from before or after the cursor.
+ var match = (!afterCursor && pos >= 0 && re.test(line.text.charAt(pos)) && matching[line.text.charAt(pos)]) ||
+ re.test(line.text.charAt(pos + 1)) && matching[line.text.charAt(++pos)];
+ if (!match) return null;
+ var dir = match.charAt(1) == ">" ? 1 : -1;
+ if (config && config.strict && (dir > 0) != (pos == where.ch)) return null;
+ var style = cm.getTokenTypeAt(Pos(where.line, pos + 1));
+
+ var found = scanForBracket(cm, Pos(where.line, pos + (dir > 0 ? 1 : 0)), dir, style || null, config);
+ if (found == null) return null;
+ return {from: Pos(where.line, pos), to: found && found.pos,
+ match: found && found.ch == match.charAt(0), forward: dir > 0};
+ }
+
+ // bracketRegex is used to specify which type of bracket to scan
+ // should be a regexp, e.g. /[[\]]/
+ //
+ // Note: If "where" is on an open bracket, then this bracket is ignored.
+ //
+ // Returns false when no bracket was found, null when it reached
+ // maxScanLines and gave up
+ function scanForBracket(cm, where, dir, style, config) {
+ var maxScanLen = (config && config.maxScanLineLength) || 10000;
+ var maxScanLines = (config && config.maxScanLines) || 1000;
+
+ var stack = [];
+ var re = bracketRegex(config)
+ var lineEnd = dir > 0 ? Math.min(where.line + maxScanLines, cm.lastLine() + 1)
+ : Math.max(cm.firstLine() - 1, where.line - maxScanLines);
+ for (var lineNo = where.line; lineNo != lineEnd; lineNo += dir) {
+ var line = cm.getLine(lineNo);
+ if (!line) continue;
+ var pos = dir > 0 ? 0 : line.length - 1, end = dir > 0 ? line.length : -1;
+ if (line.length > maxScanLen) continue;
+ if (lineNo == where.line) pos = where.ch - (dir < 0 ? 1 : 0);
+ for (; pos != end; pos += dir) {
+ var ch = line.charAt(pos);
+ if (re.test(ch) && (style === undefined || cm.getTokenTypeAt(Pos(lineNo, pos + 1)) == style)) {
+ var match = matching[ch];
+ if (match && (match.charAt(1) == ">") == (dir > 0)) stack.push(ch);
+ else if (!stack.length) return {pos: Pos(lineNo, pos), ch: ch};
+ else stack.pop();
+ }
+ }
+ }
+ return lineNo - dir == (dir > 0 ? cm.lastLine() : cm.firstLine()) ? false : null;
+ }
+
+ function matchBrackets(cm, autoclear, config) {
+ // Disable brace matching in long lines, since it'll cause hugely slow updates
+ var maxHighlightLen = cm.state.matchBrackets.maxHighlightLineLength || 1000;
+ var marks = [], ranges = cm.listSelections();
+ for (var i = 0; i < ranges.length; i++) {
+ var match = ranges[i].empty() && findMatchingBracket(cm, ranges[i].head, config);
+ if (match && cm.getLine(match.from.line).length <= maxHighlightLen) {
+ var style = match.match ? "CodeMirror-matchingbracket" : "CodeMirror-nonmatchingbracket";
+ marks.push(cm.markText(match.from, Pos(match.from.line, match.from.ch + 1), {className: style}));
+ if (match.to && cm.getLine(match.to.line).length <= maxHighlightLen)
+ marks.push(cm.markText(match.to, Pos(match.to.line, match.to.ch + 1), {className: style}));
+ }
+ }
+
+ if (marks.length) {
+ // Kludge to work around the IE bug from issue #1193, where text
+ // input stops going to the textare whever this fires.
+ if (ie_lt8 && cm.state.focused) cm.focus();
+
+ var clear = function() {
+ cm.operation(function() {
+ for (var i = 0; i < marks.length; i++) marks[i].clear();
+ });
+ };
+ if (autoclear) setTimeout(clear, 800);
+ else return clear;
+ }
+ }
+
+ function doMatchBrackets(cm) {
+ cm.operation(function() {
+ if (cm.state.matchBrackets.currentlyHighlighted) {
+ cm.state.matchBrackets.currentlyHighlighted();
+ cm.state.matchBrackets.currentlyHighlighted = null;
+ }
+ cm.state.matchBrackets.currentlyHighlighted = matchBrackets(cm, false, cm.state.matchBrackets);
+ });
+ }
+
+ CodeMirror.defineOption("matchBrackets", false, function(cm, val, old) {
+ if (old && old != CodeMirror.Init) {
+ cm.off("cursorActivity", doMatchBrackets);
+ if (cm.state.matchBrackets && cm.state.matchBrackets.currentlyHighlighted) {
+ cm.state.matchBrackets.currentlyHighlighted();
+ cm.state.matchBrackets.currentlyHighlighted = null;
+ }
+ }
+ if (val) {
+ cm.state.matchBrackets = typeof val == "object" ? val : {};
+ cm.on("cursorActivity", doMatchBrackets);
+ }
+ });
+
+ CodeMirror.defineExtension("matchBrackets", function() {matchBrackets(this, true);});
+ CodeMirror.defineExtension("findMatchingBracket", function(pos, config, oldConfig){
+ // Backwards-compatibility kludge
+ if (oldConfig || typeof config == "boolean") {
+ if (!oldConfig) {
+ config = config ? {strict: true} : null
+ } else {
+ oldConfig.strict = config
+ config = oldConfig
+ }
+ }
+ return findMatchingBracket(this, pos, config)
+ });
+ CodeMirror.defineExtension("scanForBracket", function(pos, dir, style, config){
+ return scanForBracket(this, pos, dir, style, config);
+ });
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/edit/matchtags.js b/devtools/client/shared/sourceeditor/codemirror/addon/edit/matchtags.js
new file mode 100644
index 0000000000..e50d353a5f
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/edit/matchtags.js
@@ -0,0 +1,66 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"), require("resource://devtools/client/shared/sourceeditor/codemirror/addon/fold/xml-fold.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror", "../fold/xml-fold"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ CodeMirror.defineOption("matchTags", false, function(cm, val, old) {
+ if (old && old != CodeMirror.Init) {
+ cm.off("cursorActivity", doMatchTags);
+ cm.off("viewportChange", maybeUpdateMatch);
+ clear(cm);
+ }
+ if (val) {
+ cm.state.matchBothTags = typeof val == "object" && val.bothTags;
+ cm.on("cursorActivity", doMatchTags);
+ cm.on("viewportChange", maybeUpdateMatch);
+ doMatchTags(cm);
+ }
+ });
+
+ function clear(cm) {
+ if (cm.state.tagHit) cm.state.tagHit.clear();
+ if (cm.state.tagOther) cm.state.tagOther.clear();
+ cm.state.tagHit = cm.state.tagOther = null;
+ }
+
+ function doMatchTags(cm) {
+ cm.state.failedTagMatch = false;
+ cm.operation(function() {
+ clear(cm);
+ if (cm.somethingSelected()) return;
+ var cur = cm.getCursor(), range = cm.getViewport();
+ range.from = Math.min(range.from, cur.line); range.to = Math.max(cur.line + 1, range.to);
+ var match = CodeMirror.findMatchingTag(cm, cur, range);
+ if (!match) return;
+ if (cm.state.matchBothTags) {
+ var hit = match.at == "open" ? match.open : match.close;
+ if (hit) cm.state.tagHit = cm.markText(hit.from, hit.to, {className: "CodeMirror-matchingtag"});
+ }
+ var other = match.at == "close" ? match.open : match.close;
+ if (other)
+ cm.state.tagOther = cm.markText(other.from, other.to, {className: "CodeMirror-matchingtag"});
+ else
+ cm.state.failedTagMatch = true;
+ });
+ }
+
+ function maybeUpdateMatch(cm) {
+ if (cm.state.failedTagMatch) doMatchTags(cm);
+ }
+
+ CodeMirror.commands.toMatchingTag = function(cm) {
+ var found = CodeMirror.findMatchingTag(cm, cm.getCursor());
+ if (found) {
+ var other = found.at == "close" ? found.open : found.close;
+ if (other) cm.extendSelection(other.to, other.from);
+ }
+ };
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/edit/trailingspace.js b/devtools/client/shared/sourceeditor/codemirror/addon/edit/trailingspace.js
new file mode 100644
index 0000000000..bda4084380
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/edit/trailingspace.js
@@ -0,0 +1,27 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ CodeMirror.defineOption("showTrailingSpace", false, function(cm, val, prev) {
+ if (prev == CodeMirror.Init) prev = false;
+ if (prev && !val)
+ cm.removeOverlay("trailingspace");
+ else if (!prev && val)
+ cm.addOverlay({
+ token: function(stream) {
+ for (var l = stream.string.length, i = l; i && /\s/.test(stream.string.charAt(i - 1)); --i) {}
+ if (i > stream.pos) { stream.pos = i; return null; }
+ stream.pos = l;
+ return "trailingspace";
+ },
+ name: "trailingspace"
+ });
+ });
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/fold/brace-fold.js b/devtools/client/shared/sourceeditor/codemirror/addon/fold/brace-fold.js
new file mode 100644
index 0000000000..5479b5135b
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/fold/brace-fold.js
@@ -0,0 +1,105 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+"use strict";
+
+CodeMirror.registerHelper("fold", "brace", function(cm, start) {
+ var line = start.line, lineText = cm.getLine(line);
+ var tokenType;
+
+ function findOpening(openCh) {
+ for (var at = start.ch, pass = 0;;) {
+ var found = at <= 0 ? -1 : lineText.lastIndexOf(openCh, at - 1);
+ if (found == -1) {
+ if (pass == 1) break;
+ pass = 1;
+ at = lineText.length;
+ continue;
+ }
+ if (pass == 1 && found < start.ch) break;
+ tokenType = cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1));
+ if (!/^(comment|string)/.test(tokenType)) return found + 1;
+ at = found - 1;
+ }
+ }
+
+ var startToken = "{", endToken = "}", startCh = findOpening("{");
+ if (startCh == null) {
+ startToken = "[", endToken = "]";
+ startCh = findOpening("[");
+ }
+
+ if (startCh == null) return;
+ var count = 1, lastLine = cm.lastLine(), end, endCh;
+ outer: for (var i = line; i <= lastLine; ++i) {
+ var text = cm.getLine(i), pos = i == line ? startCh : 0;
+ for (;;) {
+ var nextOpen = text.indexOf(startToken, pos), nextClose = text.indexOf(endToken, pos);
+ if (nextOpen < 0) nextOpen = text.length;
+ if (nextClose < 0) nextClose = text.length;
+ pos = Math.min(nextOpen, nextClose);
+ if (pos == text.length) break;
+ if (cm.getTokenTypeAt(CodeMirror.Pos(i, pos + 1)) == tokenType) {
+ if (pos == nextOpen) ++count;
+ else if (!--count) { end = i; endCh = pos; break outer; }
+ }
+ ++pos;
+ }
+ }
+ if (end == null || line == end) return;
+ return {from: CodeMirror.Pos(line, startCh),
+ to: CodeMirror.Pos(end, endCh)};
+});
+
+CodeMirror.registerHelper("fold", "import", function(cm, start) {
+ function hasImport(line) {
+ if (line < cm.firstLine() || line > cm.lastLine()) return null;
+ var start = cm.getTokenAt(CodeMirror.Pos(line, 1));
+ if (!/\S/.test(start.string)) start = cm.getTokenAt(CodeMirror.Pos(line, start.end + 1));
+ if (start.type != "keyword" || start.string != "import") return null;
+ // Now find closing semicolon, return its position
+ for (var i = line, e = Math.min(cm.lastLine(), line + 10); i <= e; ++i) {
+ var text = cm.getLine(i), semi = text.indexOf(";");
+ if (semi != -1) return {startCh: start.end, end: CodeMirror.Pos(i, semi)};
+ }
+ }
+
+ var startLine = start.line, has = hasImport(startLine), prev;
+ if (!has || hasImport(startLine - 1) || ((prev = hasImport(startLine - 2)) && prev.end.line == startLine - 1))
+ return null;
+ for (var end = has.end;;) {
+ var next = hasImport(end.line + 1);
+ if (next == null) break;
+ end = next.end;
+ }
+ return {from: cm.clipPos(CodeMirror.Pos(startLine, has.startCh + 1)), to: end};
+});
+
+CodeMirror.registerHelper("fold", "include", function(cm, start) {
+ function hasInclude(line) {
+ if (line < cm.firstLine() || line > cm.lastLine()) return null;
+ var start = cm.getTokenAt(CodeMirror.Pos(line, 1));
+ if (!/\S/.test(start.string)) start = cm.getTokenAt(CodeMirror.Pos(line, start.end + 1));
+ if (start.type == "meta" && start.string.slice(0, 8) == "#include") return start.start + 8;
+ }
+
+ var startLine = start.line, has = hasInclude(startLine);
+ if (has == null || hasInclude(startLine - 1) != null) return null;
+ for (var end = startLine;;) {
+ var next = hasInclude(end + 1);
+ if (next == null) break;
+ ++end;
+ }
+ return {from: CodeMirror.Pos(startLine, has + 1),
+ to: cm.clipPos(CodeMirror.Pos(end))};
+});
+
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/fold/comment-fold.js b/devtools/client/shared/sourceeditor/codemirror/addon/fold/comment-fold.js
new file mode 100644
index 0000000000..58cf1bd86d
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/fold/comment-fold.js
@@ -0,0 +1,59 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+"use strict";
+
+CodeMirror.registerGlobalHelper("fold", "comment", function(mode) {
+ return mode.blockCommentStart && mode.blockCommentEnd;
+}, function(cm, start) {
+ var mode = cm.getModeAt(start), startToken = mode.blockCommentStart, endToken = mode.blockCommentEnd;
+ if (!startToken || !endToken) return;
+ var line = start.line, lineText = cm.getLine(line);
+
+ var startCh;
+ for (var at = start.ch, pass = 0;;) {
+ var found = at <= 0 ? -1 : lineText.lastIndexOf(startToken, at - 1);
+ if (found == -1) {
+ if (pass == 1) return;
+ pass = 1;
+ at = lineText.length;
+ continue;
+ }
+ if (pass == 1 && found < start.ch) return;
+ if (/comment/.test(cm.getTokenTypeAt(CodeMirror.Pos(line, found + 1))) &&
+ (found == 0 || lineText.slice(found - endToken.length, found) == endToken ||
+ !/comment/.test(cm.getTokenTypeAt(CodeMirror.Pos(line, found))))) {
+ startCh = found + startToken.length;
+ break;
+ }
+ at = found - 1;
+ }
+
+ var depth = 1, lastLine = cm.lastLine(), end, endCh;
+ outer: for (var i = line; i <= lastLine; ++i) {
+ var text = cm.getLine(i), pos = i == line ? startCh : 0;
+ for (;;) {
+ var nextOpen = text.indexOf(startToken, pos), nextClose = text.indexOf(endToken, pos);
+ if (nextOpen < 0) nextOpen = text.length;
+ if (nextClose < 0) nextClose = text.length;
+ pos = Math.min(nextOpen, nextClose);
+ if (pos == text.length) break;
+ if (pos == nextOpen) ++depth;
+ else if (!--depth) { end = i; endCh = pos; break outer; }
+ ++pos;
+ }
+ }
+ if (end == null || line == end && endCh == startCh) return;
+ return {from: CodeMirror.Pos(line, startCh),
+ to: CodeMirror.Pos(end, endCh)};
+});
+
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/fold/foldcode.js b/devtools/client/shared/sourceeditor/codemirror/addon/fold/foldcode.js
new file mode 100644
index 0000000000..902f1a6f95
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/fold/foldcode.js
@@ -0,0 +1,152 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ function doFold(cm, pos, options, force) {
+ if (options && options.call) {
+ var finder = options;
+ options = null;
+ } else {
+ var finder = getOption(cm, options, "rangeFinder");
+ }
+ if (typeof pos == "number") pos = CodeMirror.Pos(pos, 0);
+ var minSize = getOption(cm, options, "minFoldSize");
+
+ function getRange(allowFolded) {
+ var range = finder(cm, pos);
+ if (!range || range.to.line - range.from.line < minSize) return null;
+ var marks = cm.findMarksAt(range.from);
+ for (var i = 0; i < marks.length; ++i) {
+ if (marks[i].__isFold && force !== "fold") {
+ if (!allowFolded) return null;
+ range.cleared = true;
+ marks[i].clear();
+ }
+ }
+ return range;
+ }
+
+ var range = getRange(true);
+ if (getOption(cm, options, "scanUp")) while (!range && pos.line > cm.firstLine()) {
+ pos = CodeMirror.Pos(pos.line - 1, 0);
+ range = getRange(false);
+ }
+ if (!range || range.cleared || force === "unfold") return;
+
+ var myWidget = makeWidget(cm, options);
+ CodeMirror.on(myWidget, "mousedown", function(e) {
+ myRange.clear();
+ CodeMirror.e_preventDefault(e);
+ });
+ var myRange = cm.markText(range.from, range.to, {
+ replacedWith: myWidget,
+ clearOnEnter: getOption(cm, options, "clearOnEnter"),
+ __isFold: true
+ });
+ myRange.on("clear", function(from, to) {
+ CodeMirror.signal(cm, "unfold", cm, from, to);
+ });
+ CodeMirror.signal(cm, "fold", cm, range.from, range.to);
+ }
+
+ function makeWidget(cm, options) {
+ var widget = getOption(cm, options, "widget");
+ if (typeof widget == "string") {
+ var text = document.createTextNode(widget);
+ widget = document.createElement("span");
+ widget.appendChild(text);
+ widget.className = "CodeMirror-foldmarker";
+ } else if (widget) {
+ widget = widget.cloneNode(true)
+ }
+ return widget;
+ }
+
+ // Clumsy backwards-compatible interface
+ CodeMirror.newFoldFunction = function(rangeFinder, widget) {
+ return function(cm, pos) { doFold(cm, pos, {rangeFinder: rangeFinder, widget: widget}); };
+ };
+
+ // New-style interface
+ CodeMirror.defineExtension("foldCode", function(pos, options, force) {
+ doFold(this, pos, options, force);
+ });
+
+ CodeMirror.defineExtension("isFolded", function(pos) {
+ var marks = this.findMarksAt(pos);
+ for (var i = 0; i < marks.length; ++i)
+ if (marks[i].__isFold) return true;
+ });
+
+ CodeMirror.commands.toggleFold = function(cm) {
+ cm.foldCode(cm.getCursor());
+ };
+ CodeMirror.commands.fold = function(cm) {
+ cm.foldCode(cm.getCursor(), null, "fold");
+ };
+ CodeMirror.commands.unfold = function(cm) {
+ cm.foldCode(cm.getCursor(), null, "unfold");
+ };
+ CodeMirror.commands.foldAll = function(cm) {
+ cm.operation(function() {
+ for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++)
+ cm.foldCode(CodeMirror.Pos(i, 0), null, "fold");
+ });
+ };
+ CodeMirror.commands.unfoldAll = function(cm) {
+ cm.operation(function() {
+ for (var i = cm.firstLine(), e = cm.lastLine(); i <= e; i++)
+ cm.foldCode(CodeMirror.Pos(i, 0), null, "unfold");
+ });
+ };
+
+ CodeMirror.registerHelper("fold", "combine", function() {
+ var funcs = Array.prototype.slice.call(arguments, 0);
+ return function(cm, start) {
+ for (var i = 0; i < funcs.length; ++i) {
+ var found = funcs[i](cm, start);
+ if (found) return found;
+ }
+ };
+ });
+
+ CodeMirror.registerHelper("fold", "auto", function(cm, start) {
+ var helpers = cm.getHelpers(start, "fold");
+ for (var i = 0; i < helpers.length; i++) {
+ var cur = helpers[i](cm, start);
+ if (cur) return cur;
+ }
+ });
+
+ var defaultOptions = {
+ rangeFinder: CodeMirror.fold.auto,
+ widget: "\u2194",
+ minFoldSize: 0,
+ scanUp: false,
+ clearOnEnter: true
+ };
+
+ CodeMirror.defineOption("foldOptions", null);
+
+ function getOption(cm, options, name) {
+ if (options && options[name] !== undefined)
+ return options[name];
+ var editorOptions = cm.options.foldOptions;
+ if (editorOptions && editorOptions[name] !== undefined)
+ return editorOptions[name];
+ return defaultOptions[name];
+ }
+
+ CodeMirror.defineExtension("foldOption", function(options, name) {
+ return getOption(this, options, name);
+ });
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/fold/foldgutter.css b/devtools/client/shared/sourceeditor/codemirror/addon/fold/foldgutter.css
new file mode 100644
index 0000000000..ad19ae2d3e
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/fold/foldgutter.css
@@ -0,0 +1,20 @@
+.CodeMirror-foldmarker {
+ color: blue;
+ text-shadow: #b9f 1px 1px 2px, #b9f -1px -1px 2px, #b9f 1px -1px 2px, #b9f -1px 1px 2px;
+ font-family: arial;
+ line-height: .3;
+ cursor: pointer;
+}
+.CodeMirror-foldgutter {
+ width: .7em;
+}
+.CodeMirror-foldgutter-open,
+.CodeMirror-foldgutter-folded {
+ cursor: pointer;
+}
+.CodeMirror-foldgutter-open:after {
+ content: "\25BE";
+}
+.CodeMirror-foldgutter-folded:after {
+ content: "\25B8";
+}
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/fold/foldgutter.js b/devtools/client/shared/sourceeditor/codemirror/addon/fold/foldgutter.js
new file mode 100644
index 0000000000..a41fbfd21e
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/fold/foldgutter.js
@@ -0,0 +1,151 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"), require("resource://devtools/client/shared/sourceeditor/codemirror/addon/fold/foldcode.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror", "./foldcode"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ CodeMirror.defineOption("foldGutter", false, function(cm, val, old) {
+ if (old && old != CodeMirror.Init) {
+ cm.clearGutter(cm.state.foldGutter.options.gutter);
+ cm.state.foldGutter = null;
+ cm.off("gutterClick", onGutterClick);
+ cm.off("changes", onChange);
+ cm.off("viewportChange", onViewportChange);
+ cm.off("fold", onFold);
+ cm.off("unfold", onFold);
+ cm.off("swapDoc", onChange);
+ }
+ if (val) {
+ cm.state.foldGutter = new State(parseOptions(val));
+ updateInViewport(cm);
+ cm.on("gutterClick", onGutterClick);
+ cm.on("changes", onChange);
+ cm.on("viewportChange", onViewportChange);
+ cm.on("fold", onFold);
+ cm.on("unfold", onFold);
+ cm.on("swapDoc", onChange);
+ }
+ });
+
+ var Pos = CodeMirror.Pos;
+
+ function State(options) {
+ this.options = options;
+ this.from = this.to = 0;
+ }
+
+ function parseOptions(opts) {
+ if (opts === true) opts = {};
+ if (opts.gutter == null) opts.gutter = "CodeMirror-foldgutter";
+ if (opts.indicatorOpen == null) opts.indicatorOpen = "CodeMirror-foldgutter-open";
+ if (opts.indicatorFolded == null) opts.indicatorFolded = "CodeMirror-foldgutter-folded";
+ return opts;
+ }
+
+ function isFolded(cm, line) {
+ var marks = cm.findMarks(Pos(line, 0), Pos(line + 1, 0));
+ for (var i = 0; i < marks.length; ++i) {
+ if (marks[i].__isFold) {
+ var fromPos = marks[i].find(-1);
+ if (fromPos && fromPos.line === line)
+ return marks[i];
+ }
+ }
+ }
+
+ function marker(spec) {
+ if (typeof spec == "string") {
+ var elt = document.createElement("div");
+ elt.className = spec + " CodeMirror-guttermarker-subtle";
+ return elt;
+ } else {
+ return spec.cloneNode(true);
+ }
+ }
+
+ function updateFoldInfo(cm, from, to) {
+ var opts = cm.state.foldGutter.options, cur = from;
+ var minSize = cm.foldOption(opts, "minFoldSize");
+ var func = cm.foldOption(opts, "rangeFinder");
+ cm.eachLine(from, to, function(line) {
+ var mark = null;
+ if (isFolded(cm, cur)) {
+ mark = marker(opts.indicatorFolded);
+ } else {
+ var pos = Pos(cur, 0);
+ var range = func && func(cm, pos);
+ if (range && range.to.line - range.from.line >= minSize)
+ mark = marker(opts.indicatorOpen);
+ }
+ cm.setGutterMarker(line, opts.gutter, mark);
+ ++cur;
+ });
+ }
+
+ function updateInViewport(cm) {
+ var vp = cm.getViewport(), state = cm.state.foldGutter;
+ if (!state) return;
+ cm.operation(function() {
+ updateFoldInfo(cm, vp.from, vp.to);
+ });
+ state.from = vp.from; state.to = vp.to;
+ }
+
+ function onGutterClick(cm, line, gutter) {
+ var state = cm.state.foldGutter;
+ if (!state) return;
+ var opts = state.options;
+ if (gutter != opts.gutter) return;
+ var folded = isFolded(cm, line);
+ if (folded) folded.clear();
+ else cm.foldCode(Pos(line, 0), opts);
+ }
+
+ function onChange(cm) {
+ var state = cm.state.foldGutter;
+ if (!state) return;
+ var opts = state.options;
+ state.from = state.to = 0;
+ clearTimeout(state.changeUpdate);
+ state.changeUpdate = setTimeout(function() { updateInViewport(cm); }, opts.foldOnChangeTimeSpan || 600);
+ }
+
+ function onViewportChange(cm) {
+ var state = cm.state.foldGutter;
+ if (!state) return;
+ var opts = state.options;
+ clearTimeout(state.changeUpdate);
+ state.changeUpdate = setTimeout(function() {
+ var vp = cm.getViewport();
+ if (state.from == state.to || vp.from - state.to > 20 || state.from - vp.to > 20) {
+ updateInViewport(cm);
+ } else {
+ cm.operation(function() {
+ if (vp.from < state.from) {
+ updateFoldInfo(cm, vp.from, state.from);
+ state.from = vp.from;
+ }
+ if (vp.to > state.to) {
+ updateFoldInfo(cm, state.to, vp.to);
+ state.to = vp.to;
+ }
+ });
+ }
+ }, opts.updateViewportTimeSpan || 400);
+ }
+
+ function onFold(cm, from) {
+ var state = cm.state.foldGutter;
+ if (!state) return;
+ var line = from.line;
+ if (line >= state.from && line < state.to)
+ updateFoldInfo(cm, line, line + 1);
+ }
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/fold/indent-fold.js b/devtools/client/shared/sourceeditor/codemirror/addon/fold/indent-fold.js
new file mode 100644
index 0000000000..be72c2447d
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/fold/indent-fold.js
@@ -0,0 +1,48 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+"use strict";
+
+function lineIndent(cm, lineNo) {
+ var text = cm.getLine(lineNo)
+ var spaceTo = text.search(/\S/)
+ if (spaceTo == -1 || /\bcomment\b/.test(cm.getTokenTypeAt(CodeMirror.Pos(lineNo, spaceTo + 1))))
+ return -1
+ return CodeMirror.countColumn(text, null, cm.getOption("tabSize"))
+}
+
+CodeMirror.registerHelper("fold", "indent", function(cm, start) {
+ var myIndent = lineIndent(cm, start.line)
+ if (myIndent < 0) return
+ var lastLineInFold = null
+
+ // Go through lines until we find a line that definitely doesn't belong in
+ // the block we're folding, or to the end.
+ for (var i = start.line + 1, end = cm.lastLine(); i <= end; ++i) {
+ var indent = lineIndent(cm, i)
+ if (indent == -1) {
+ } else if (indent > myIndent) {
+ // Lines with a greater indent are considered part of the block.
+ lastLineInFold = i;
+ } else {
+ // If this line has non-space, non-comment content, and is
+ // indented less or equal to the start line, it is the start of
+ // another block.
+ break;
+ }
+ }
+ if (lastLineInFold) return {
+ from: CodeMirror.Pos(start.line, cm.getLine(start.line).length),
+ to: CodeMirror.Pos(lastLineInFold, cm.getLine(lastLineInFold).length)
+ };
+});
+
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/fold/markdown-fold.js b/devtools/client/shared/sourceeditor/codemirror/addon/fold/markdown-fold.js
new file mode 100644
index 0000000000..133a55f8c1
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/fold/markdown-fold.js
@@ -0,0 +1,49 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+"use strict";
+
+CodeMirror.registerHelper("fold", "markdown", function(cm, start) {
+ var maxDepth = 100;
+
+ function isHeader(lineNo) {
+ var tokentype = cm.getTokenTypeAt(CodeMirror.Pos(lineNo, 0));
+ return tokentype && /\bheader\b/.test(tokentype);
+ }
+
+ function headerLevel(lineNo, line, nextLine) {
+ var match = line && line.match(/^#+/);
+ if (match && isHeader(lineNo)) return match[0].length;
+ match = nextLine && nextLine.match(/^[=\-]+\s*$/);
+ if (match && isHeader(lineNo + 1)) return nextLine[0] == "=" ? 1 : 2;
+ return maxDepth;
+ }
+
+ var firstLine = cm.getLine(start.line), nextLine = cm.getLine(start.line + 1);
+ var level = headerLevel(start.line, firstLine, nextLine);
+ if (level === maxDepth) return undefined;
+
+ var lastLineNo = cm.lastLine();
+ var end = start.line, nextNextLine = cm.getLine(end + 2);
+ while (end < lastLineNo) {
+ if (headerLevel(end + 1, nextLine, nextNextLine) <= level) break;
+ ++end;
+ nextLine = nextNextLine;
+ nextNextLine = cm.getLine(end + 2);
+ }
+
+ return {
+ from: CodeMirror.Pos(start.line, firstLine.length),
+ to: CodeMirror.Pos(end, cm.getLine(end).length)
+ };
+});
+
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/fold/xml-fold.js b/devtools/client/shared/sourceeditor/codemirror/addon/fold/xml-fold.js
new file mode 100644
index 0000000000..34d69251b2
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/fold/xml-fold.js
@@ -0,0 +1,184 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ var Pos = CodeMirror.Pos;
+ function cmp(a, b) { return a.line - b.line || a.ch - b.ch; }
+
+ var nameStartChar = "A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD";
+ var nameChar = nameStartChar + "\-\:\.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040";
+ var xmlTagStart = new RegExp("<(/?)([" + nameStartChar + "][" + nameChar + "]*)", "g");
+
+ function Iter(cm, line, ch, range) {
+ this.line = line; this.ch = ch;
+ this.cm = cm; this.text = cm.getLine(line);
+ this.min = range ? Math.max(range.from, cm.firstLine()) : cm.firstLine();
+ this.max = range ? Math.min(range.to - 1, cm.lastLine()) : cm.lastLine();
+ }
+
+ function tagAt(iter, ch) {
+ var type = iter.cm.getTokenTypeAt(Pos(iter.line, ch));
+ return type && /\btag\b/.test(type);
+ }
+
+ function nextLine(iter) {
+ if (iter.line >= iter.max) return;
+ iter.ch = 0;
+ iter.text = iter.cm.getLine(++iter.line);
+ return true;
+ }
+ function prevLine(iter) {
+ if (iter.line <= iter.min) return;
+ iter.text = iter.cm.getLine(--iter.line);
+ iter.ch = iter.text.length;
+ return true;
+ }
+
+ function toTagEnd(iter) {
+ for (;;) {
+ var gt = iter.text.indexOf(">", iter.ch);
+ if (gt == -1) { if (nextLine(iter)) continue; else return; }
+ if (!tagAt(iter, gt + 1)) { iter.ch = gt + 1; continue; }
+ var lastSlash = iter.text.lastIndexOf("/", gt);
+ var selfClose = lastSlash > -1 && !/\S/.test(iter.text.slice(lastSlash + 1, gt));
+ iter.ch = gt + 1;
+ return selfClose ? "selfClose" : "regular";
+ }
+ }
+ function toTagStart(iter) {
+ for (;;) {
+ var lt = iter.ch ? iter.text.lastIndexOf("<", iter.ch - 1) : -1;
+ if (lt == -1) { if (prevLine(iter)) continue; else return; }
+ if (!tagAt(iter, lt + 1)) { iter.ch = lt; continue; }
+ xmlTagStart.lastIndex = lt;
+ iter.ch = lt;
+ var match = xmlTagStart.exec(iter.text);
+ if (match && match.index == lt) return match;
+ }
+ }
+
+ function toNextTag(iter) {
+ for (;;) {
+ xmlTagStart.lastIndex = iter.ch;
+ var found = xmlTagStart.exec(iter.text);
+ if (!found) { if (nextLine(iter)) continue; else return; }
+ if (!tagAt(iter, found.index + 1)) { iter.ch = found.index + 1; continue; }
+ iter.ch = found.index + found[0].length;
+ return found;
+ }
+ }
+ function toPrevTag(iter) {
+ for (;;) {
+ var gt = iter.ch ? iter.text.lastIndexOf(">", iter.ch - 1) : -1;
+ if (gt == -1) { if (prevLine(iter)) continue; else return; }
+ if (!tagAt(iter, gt + 1)) { iter.ch = gt; continue; }
+ var lastSlash = iter.text.lastIndexOf("/", gt);
+ var selfClose = lastSlash > -1 && !/\S/.test(iter.text.slice(lastSlash + 1, gt));
+ iter.ch = gt + 1;
+ return selfClose ? "selfClose" : "regular";
+ }
+ }
+
+ function findMatchingClose(iter, tag) {
+ var stack = [];
+ for (;;) {
+ var next = toNextTag(iter), end, startLine = iter.line, startCh = iter.ch - (next ? next[0].length : 0);
+ if (!next || !(end = toTagEnd(iter))) return;
+ if (end == "selfClose") continue;
+ if (next[1]) { // closing tag
+ for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == next[2]) {
+ stack.length = i;
+ break;
+ }
+ if (i < 0 && (!tag || tag == next[2])) return {
+ tag: next[2],
+ from: Pos(startLine, startCh),
+ to: Pos(iter.line, iter.ch)
+ };
+ } else { // opening tag
+ stack.push(next[2]);
+ }
+ }
+ }
+ function findMatchingOpen(iter, tag) {
+ var stack = [];
+ for (;;) {
+ var prev = toPrevTag(iter);
+ if (!prev) return;
+ if (prev == "selfClose") { toTagStart(iter); continue; }
+ var endLine = iter.line, endCh = iter.ch;
+ var start = toTagStart(iter);
+ if (!start) return;
+ if (start[1]) { // closing tag
+ stack.push(start[2]);
+ } else { // opening tag
+ for (var i = stack.length - 1; i >= 0; --i) if (stack[i] == start[2]) {
+ stack.length = i;
+ break;
+ }
+ if (i < 0 && (!tag || tag == start[2])) return {
+ tag: start[2],
+ from: Pos(iter.line, iter.ch),
+ to: Pos(endLine, endCh)
+ };
+ }
+ }
+ }
+
+ CodeMirror.registerHelper("fold", "xml", function(cm, start) {
+ var iter = new Iter(cm, start.line, 0);
+ for (;;) {
+ var openTag = toNextTag(iter)
+ if (!openTag || iter.line != start.line) return
+ var end = toTagEnd(iter)
+ if (!end) return
+ if (!openTag[1] && end != "selfClose") {
+ var startPos = Pos(iter.line, iter.ch);
+ var endPos = findMatchingClose(iter, openTag[2]);
+ return endPos && cmp(endPos.from, startPos) > 0 ? {from: startPos, to: endPos.from} : null
+ }
+ }
+ });
+ CodeMirror.findMatchingTag = function(cm, pos, range) {
+ var iter = new Iter(cm, pos.line, pos.ch, range);
+ if (iter.text.indexOf(">") == -1 && iter.text.indexOf("<") == -1) return;
+ var end = toTagEnd(iter), to = end && Pos(iter.line, iter.ch);
+ var start = end && toTagStart(iter);
+ if (!end || !start || cmp(iter, pos) > 0) return;
+ var here = {from: Pos(iter.line, iter.ch), to: to, tag: start[2]};
+ if (end == "selfClose") return {open: here, close: null, at: "open"};
+
+ if (start[1]) { // closing tag
+ return {open: findMatchingOpen(iter, start[2]), close: here, at: "close"};
+ } else { // opening tag
+ iter = new Iter(cm, to.line, to.ch, range);
+ return {open: here, close: findMatchingClose(iter, start[2]), at: "open"};
+ }
+ };
+
+ CodeMirror.findEnclosingTag = function(cm, pos, range, tag) {
+ var iter = new Iter(cm, pos.line, pos.ch, range);
+ for (;;) {
+ var open = findMatchingOpen(iter, tag);
+ if (!open) break;
+ var forward = new Iter(cm, pos.line, pos.ch, range);
+ var close = findMatchingClose(forward, open.tag);
+ if (close) return {open: open, close: close};
+ }
+ };
+
+ // Used by addon/edit/closetag.js
+ CodeMirror.scanForClosingTag = function(cm, pos, name, end) {
+ var iter = new Iter(cm, pos.line, pos.ch, end ? {from: 0, to: end} : null);
+ return findMatchingClose(iter, name);
+ };
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/runmode/runmode.js b/devtools/client/shared/sourceeditor/codemirror/addon/runmode/runmode.js
new file mode 100644
index 0000000000..7f23196ac1
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/runmode/runmode.js
@@ -0,0 +1,72 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+"use strict";
+
+CodeMirror.runMode = function(string, modespec, callback, options) {
+ var mode = CodeMirror.getMode(CodeMirror.defaults, modespec);
+ var ie = /MSIE \d/.test(navigator.userAgent);
+ var ie_lt9 = ie && (document.documentMode == null || document.documentMode < 9);
+
+ if (callback.appendChild) {
+ var tabSize = (options && options.tabSize) || CodeMirror.defaults.tabSize;
+ var node = callback, col = 0;
+ node.innerHTML = "";
+ callback = function(text, style) {
+ if (text == "\n") {
+ // Emitting LF or CRLF on IE8 or earlier results in an incorrect display.
+ // Emitting a carriage return makes everything ok.
+ node.appendChild(document.createTextNode(ie_lt9 ? '\r' : text));
+ col = 0;
+ return;
+ }
+ var content = "";
+ // replace tabs
+ for (var pos = 0;;) {
+ var idx = text.indexOf("\t", pos);
+ if (idx == -1) {
+ content += text.slice(pos);
+ col += text.length - pos;
+ break;
+ } else {
+ col += idx - pos;
+ content += text.slice(pos, idx);
+ var size = tabSize - col % tabSize;
+ col += size;
+ for (var i = 0; i < size; ++i) content += " ";
+ pos = idx + 1;
+ }
+ }
+
+ if (style) {
+ var sp = node.appendChild(document.createElement("span"));
+ sp.className = "cm-" + style.replace(/ +/g, " cm-");
+ sp.appendChild(document.createTextNode(content));
+ } else {
+ node.appendChild(document.createTextNode(content));
+ }
+ };
+ }
+
+ var lines = CodeMirror.splitLines(string), state = (options && options.state) || CodeMirror.startState(mode);
+ for (var i = 0, e = lines.length; i < e; ++i) {
+ if (i) callback("\n");
+ var stream = new CodeMirror.StringStream(lines[i]);
+ if (!stream.string && mode.blankLine) mode.blankLine(state);
+ while (!stream.eol()) {
+ var style = mode.token(stream, state);
+ callback(stream.current(), style, i, stream.start, state);
+ stream.start = stream.pos;
+ }
+ }
+};
+
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/scroll/annotatescrollbar.js b/devtools/client/shared/sourceeditor/codemirror/addon/scroll/annotatescrollbar.js
new file mode 100644
index 0000000000..c12e44cda5
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/scroll/annotatescrollbar.js
@@ -0,0 +1,128 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(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.defineExtension("annotateScrollbar", function(options) {
+ if (typeof options == "string") options = {className: options};
+ return new Annotation(this, options);
+ });
+
+ CodeMirror.defineOption("scrollButtonHeight", 0);
+
+ function Annotation(cm, options) {
+ this.cm = cm;
+ this.options = options;
+ this.buttonHeight = options.scrollButtonHeight || cm.getOption("scrollButtonHeight");
+ this.annotations = [];
+ this.doRedraw = this.doUpdate = null;
+ this.div = cm.getWrapperElement().appendChild(document.createElement("div"));
+ this.div.style.cssText = "position: absolute; right: 0; top: 0; z-index: 7; pointer-events: none";
+ this.computeScale();
+
+ function scheduleRedraw(delay) {
+ clearTimeout(self.doRedraw);
+ self.doRedraw = setTimeout(function() { self.redraw(); }, delay);
+ }
+
+ var self = this;
+ cm.on("refresh", this.resizeHandler = function() {
+ clearTimeout(self.doUpdate);
+ self.doUpdate = setTimeout(function() {
+ if (self.computeScale()) scheduleRedraw(20);
+ }, 100);
+ });
+ cm.on("markerAdded", this.resizeHandler);
+ cm.on("markerCleared", this.resizeHandler);
+ if (options.listenForChanges !== false)
+ cm.on("changes", this.changeHandler = function() {
+ scheduleRedraw(250);
+ });
+ }
+
+ Annotation.prototype.computeScale = function() {
+ var cm = this.cm;
+ var hScale = (cm.getWrapperElement().clientHeight - cm.display.barHeight - this.buttonHeight * 2) /
+ cm.getScrollerElement().scrollHeight
+ if (hScale != this.hScale) {
+ this.hScale = hScale;
+ return true;
+ }
+ };
+
+ Annotation.prototype.update = function(annotations) {
+ this.annotations = annotations;
+ this.redraw();
+ };
+
+ Annotation.prototype.redraw = function(compute) {
+ if (compute !== false) this.computeScale();
+ var cm = this.cm, hScale = this.hScale;
+
+ var frag = document.createDocumentFragment(), anns = this.annotations;
+
+ var wrapping = cm.getOption("lineWrapping");
+ var singleLineH = wrapping && cm.defaultTextHeight() * 1.5;
+ var curLine = null, curLineObj = null;
+
+ function getY(pos, top) {
+ if (curLine != pos.line) {
+ curLine = pos.line
+ curLineObj = cm.getLineHandle(pos.line)
+ var visual = cm.getLineHandleVisualStart(curLineObj)
+ if (visual != curLineObj) {
+ curLine = cm.getLineNumber(visual)
+ curLineObj = visual
+ }
+ }
+ if ((curLineObj.widgets && curLineObj.widgets.length) ||
+ (wrapping && curLineObj.height > singleLineH))
+ return cm.charCoords(pos, "local")[top ? "top" : "bottom"];
+ var topY = cm.heightAtLine(curLineObj, "local");
+ return topY + (top ? 0 : curLineObj.height);
+ }
+
+ var lastLine = cm.lastLine()
+ if (cm.display.barWidth) for (var i = 0, nextTop; i < anns.length; i++) {
+ var ann = anns[i];
+ if (ann.to.line > lastLine) continue;
+ var top = nextTop || getY(ann.from, true) * hScale;
+ var bottom = getY(ann.to, false) * hScale;
+ while (i < anns.length - 1) {
+ if (anns[i + 1].to.line > lastLine) break;
+ nextTop = getY(anns[i + 1].from, true) * hScale;
+ if (nextTop > bottom + .9) break;
+ ann = anns[++i];
+ bottom = getY(ann.to, false) * hScale;
+ }
+ if (bottom == top) continue;
+ var height = Math.max(bottom - top, 3);
+
+ var elt = frag.appendChild(document.createElement("div"));
+ elt.style.cssText = "position: absolute; right: 0px; width: " + Math.max(cm.display.barWidth - 1, 2) + "px; top: "
+ + (top + this.buttonHeight) + "px; height: " + height + "px";
+ elt.className = this.options.className;
+ if (ann.id) {
+ elt.setAttribute("annotation-id", ann.id);
+ }
+ }
+ this.div.textContent = "";
+ this.div.appendChild(frag);
+ };
+
+ Annotation.prototype.clear = function() {
+ this.cm.off("refresh", this.resizeHandler);
+ this.cm.off("markerAdded", this.resizeHandler);
+ this.cm.off("markerCleared", this.resizeHandler);
+ if (this.changeHandler) this.cm.off("changes", this.changeHandler);
+ this.div.parentNode.removeChild(this.div);
+ };
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/search/match-highlighter.js b/devtools/client/shared/sourceeditor/codemirror/addon/search/match-highlighter.js
new file mode 100644
index 0000000000..d829c3808b
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/search/match-highlighter.js
@@ -0,0 +1,165 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+// Highlighting text that matches the selection
+//
+// Defines an option highlightSelectionMatches, which, when enabled,
+// will style strings that match the selection throughout the
+// document.
+//
+// The option can be set to true to simply enable it, or to a
+// {minChars, style, wordsOnly, showToken, delay} object to explicitly
+// configure it. minChars is the minimum amount of characters that should be
+// selected for the behavior to occur, and style is the token style to
+// apply to the matches. This will be prefixed by "cm-" to create an
+// actual CSS class name. If wordsOnly is enabled, the matches will be
+// highlighted only if the selected text is a word. showToken, when enabled,
+// will cause the current token to be highlighted when nothing is selected.
+// delay is used to specify how much time to wait, in milliseconds, before
+// highlighting the matches. If annotateScrollbar is enabled, the occurences
+// will be highlighted on the scrollbar via the matchesonscrollbar addon.
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"), require("resource://devtools/client/shared/sourceeditor/codemirror/addon/search/matchesonscrollbar.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror", "./matchesonscrollbar"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ var defaults = {
+ style: "matchhighlight",
+ minChars: 2,
+ delay: 100,
+ wordsOnly: false,
+ annotateScrollbar: false,
+ showToken: false,
+ trim: true
+ }
+
+ function State(options) {
+ this.options = {}
+ for (var name in defaults)
+ this.options[name] = (options && options.hasOwnProperty(name) ? options : defaults)[name]
+ this.overlay = this.timeout = null;
+ this.matchesonscroll = null;
+ this.active = false;
+ }
+
+ CodeMirror.defineOption("highlightSelectionMatches", false, function(cm, val, old) {
+ if (old && old != CodeMirror.Init) {
+ removeOverlay(cm);
+ clearTimeout(cm.state.matchHighlighter.timeout);
+ cm.state.matchHighlighter = null;
+ cm.off("cursorActivity", cursorActivity);
+ cm.off("focus", onFocus)
+ }
+ if (val) {
+ var state = cm.state.matchHighlighter = new State(val);
+ if (cm.hasFocus()) {
+ state.active = true
+ highlightMatches(cm)
+ } else {
+ cm.on("focus", onFocus)
+ }
+ cm.on("cursorActivity", cursorActivity);
+ }
+ });
+
+ function cursorActivity(cm) {
+ var state = cm.state.matchHighlighter;
+ if (state.active || cm.hasFocus()) scheduleHighlight(cm, state)
+ }
+
+ function onFocus(cm) {
+ var state = cm.state.matchHighlighter
+ if (!state.active) {
+ state.active = true
+ scheduleHighlight(cm, state)
+ }
+ }
+
+ function scheduleHighlight(cm, state) {
+ clearTimeout(state.timeout);
+ state.timeout = setTimeout(function() {highlightMatches(cm);}, state.options.delay);
+ }
+
+ function addOverlay(cm, query, hasBoundary, style) {
+ var state = cm.state.matchHighlighter;
+ cm.addOverlay(state.overlay = makeOverlay(query, hasBoundary, style));
+ if (state.options.annotateScrollbar && cm.showMatchesOnScrollbar) {
+ var searchFor = hasBoundary ? new RegExp("\\b" + query.replace(/[\\\[.+*?(){|^$]/g, "\\$&") + "\\b") : query;
+ state.matchesonscroll = cm.showMatchesOnScrollbar(searchFor, false,
+ {className: "CodeMirror-selection-highlight-scrollbar"});
+ }
+ }
+
+ function removeOverlay(cm) {
+ var state = cm.state.matchHighlighter;
+ if (state.overlay) {
+ cm.removeOverlay(state.overlay);
+ state.overlay = null;
+ if (state.matchesonscroll) {
+ state.matchesonscroll.clear();
+ state.matchesonscroll = null;
+ }
+ }
+ }
+
+ function highlightMatches(cm) {
+ cm.operation(function() {
+ var state = cm.state.matchHighlighter;
+ removeOverlay(cm);
+ if (!cm.somethingSelected() && state.options.showToken) {
+ var re = state.options.showToken === true ? /[\w$]/ : state.options.showToken;
+ var cur = cm.getCursor(), line = cm.getLine(cur.line), start = cur.ch, end = start;
+ while (start && re.test(line.charAt(start - 1))) --start;
+ while (end < line.length && re.test(line.charAt(end))) ++end;
+ if (start < end)
+ addOverlay(cm, line.slice(start, end), re, state.options.style);
+ return;
+ }
+ var from = cm.getCursor("from"), to = cm.getCursor("to");
+ if (from.line != to.line) return;
+ if (state.options.wordsOnly && !isWord(cm, from, to)) return;
+ var selection = cm.getRange(from, to)
+ if (state.options.trim) selection = selection.replace(/^\s+|\s+$/g, "")
+ if (selection.length >= state.options.minChars)
+ addOverlay(cm, selection, false, state.options.style);
+ });
+ }
+
+ function isWord(cm, from, to) {
+ var str = cm.getRange(from, to);
+ if (str.match(/^\w+$/) !== null) {
+ if (from.ch > 0) {
+ var pos = {line: from.line, ch: from.ch - 1};
+ var chr = cm.getRange(pos, from);
+ if (chr.match(/\W/) === null) return false;
+ }
+ if (to.ch < cm.getLine(from.line).length) {
+ var pos = {line: to.line, ch: to.ch + 1};
+ var chr = cm.getRange(to, pos);
+ if (chr.match(/\W/) === null) return false;
+ }
+ return true;
+ } else return false;
+ }
+
+ function boundariesAround(stream, re) {
+ return (!stream.start || !re.test(stream.string.charAt(stream.start - 1))) &&
+ (stream.pos == stream.string.length || !re.test(stream.string.charAt(stream.pos)));
+ }
+
+ function makeOverlay(query, hasBoundary, style) {
+ return {token: function(stream) {
+ if (stream.match(query) &&
+ (!hasBoundary || boundariesAround(stream, hasBoundary)))
+ return style;
+ stream.next();
+ stream.skipTo(query.charAt(0)) || stream.skipToEnd();
+ }};
+ }
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/search/matchesonscrollbar.js b/devtools/client/shared/sourceeditor/codemirror/addon/search/matchesonscrollbar.js
new file mode 100644
index 0000000000..0b505947d9
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/search/matchesonscrollbar.js
@@ -0,0 +1,97 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("../../lib/codemirror"), require("./searchcursor"), require("../scroll/annotatescrollbar"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror", "./searchcursor", "../scroll/annotatescrollbar"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+ })(function(CodeMirror) {
+ "use strict";
+
+ CodeMirror.defineExtension("showMatchesOnScrollbar", function(query, caseFold, options) {
+ if (typeof options == "string") options = {className: options};
+ if (!options) options = {};
+ return new SearchAnnotation(this, query, caseFold, options);
+ });
+
+ function SearchAnnotation(cm, query, caseFold, options) {
+ this.cm = cm;
+ this.options = options;
+ var annotateOptions = {listenForChanges: false};
+ for (var prop in options) annotateOptions[prop] = options[prop];
+ if (!annotateOptions.className) annotateOptions.className = "CodeMirror-search-match";
+ this.annotation = cm.annotateScrollbar(annotateOptions);
+ this.query = query;
+ this.caseFold = caseFold;
+ this.gap = {from: cm.firstLine(), to: cm.lastLine() + 1};
+ this.matches = [];
+ this.update = null;
+
+ this.findMatches();
+ this.annotation.update(this.matches);
+
+ var self = this;
+ cm.on("change", this.changeHandler = function(_cm, change) { self.onChange(change); });
+ }
+
+ var MAX_MATCHES = 1000;
+
+ SearchAnnotation.prototype.findMatches = function() {
+ if (!this.gap) return;
+ for (var i = 0; i < this.matches.length; i++) {
+ var match = this.matches[i];
+ if (match.from.line >= this.gap.to) break;
+ if (match.to.line >= this.gap.from) this.matches.splice(i--, 1);
+ }
+ var cursor = this.cm.getSearchCursor(this.query, CodeMirror.Pos(this.gap.from, 0), {caseFold: this.caseFold, multiline: this.options.multiline});
+ var maxMatches = this.options && this.options.maxMatches || MAX_MATCHES;
+ while (cursor.findNext()) {
+ var match = {from: cursor.from(), to: cursor.to()};
+ if (match.from.line >= this.gap.to) break;
+ this.matches.splice(i++, 0, match);
+ if (this.matches.length > maxMatches) break;
+ }
+ this.gap = null;
+ };
+
+ function offsetLine(line, changeStart, sizeChange) {
+ if (line <= changeStart) return line;
+ return Math.max(changeStart, line + sizeChange);
+ }
+
+ SearchAnnotation.prototype.onChange = function(change) {
+ var startLine = change.from.line;
+ var endLine = CodeMirror.changeEnd(change).line;
+ var sizeChange = endLine - change.to.line;
+ if (this.gap) {
+ this.gap.from = Math.min(offsetLine(this.gap.from, startLine, sizeChange), change.from.line);
+ this.gap.to = Math.max(offsetLine(this.gap.to, startLine, sizeChange), change.from.line);
+ } else {
+ this.gap = {from: change.from.line, to: endLine + 1};
+ }
+
+ if (sizeChange) for (var i = 0; i < this.matches.length; i++) {
+ var match = this.matches[i];
+ var newFrom = offsetLine(match.from.line, startLine, sizeChange);
+ if (newFrom != match.from.line) match.from = CodeMirror.Pos(newFrom, match.from.ch);
+ var newTo = offsetLine(match.to.line, startLine, sizeChange);
+ if (newTo != match.to.line) match.to = CodeMirror.Pos(newTo, match.to.ch);
+ }
+ clearTimeout(this.update);
+ var self = this;
+ this.update = setTimeout(function() { self.updateAfterChange(); }, 250);
+ };
+
+ SearchAnnotation.prototype.updateAfterChange = function() {
+ this.findMatches();
+ this.annotation.update(this.matches);
+ };
+
+ SearchAnnotation.prototype.clear = function() {
+ this.cm.off("change", this.changeHandler);
+ this.annotation.clear();
+ };
+ }); \ No newline at end of file
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/search/search.js b/devtools/client/shared/sourceeditor/codemirror/addon/search/search.js
new file mode 100644
index 0000000000..c7fcb75a38
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/search/search.js
@@ -0,0 +1,323 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+// Define search commands. Depends on dialog.js or another
+// implementation of the openDialog method.
+
+// Replace works a little oddly -- it will do the replace on the next
+// Ctrl-G (or whatever is bound to findNext) press. You prevent a
+// replace by making sure the match is no longer selected when hitting
+// Ctrl-G.
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"), require("resource://devtools/client/shared/sourceeditor/codemirror/addon/search/searchcursor.js"), require("resource://devtools/client/shared/sourceeditor/codemirror/addon/dialog/dialog.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror", "./searchcursor", "../dialog/dialog"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ function searchOverlay(query, caseInsensitive) {
+ if (typeof query == "string")
+ query = new RegExp(query.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&"), caseInsensitive ? "gi" : "g");
+ else if (!query.global)
+ query = new RegExp(query.source, query.ignoreCase ? "gi" : "g");
+
+ return {token: function(stream) {
+ query.lastIndex = stream.pos;
+ var match = query.exec(stream.string);
+ if (match && match.index == stream.pos) {
+ stream.pos += match[0].length || 1;
+ return "searching";
+ } else if (match) {
+ stream.pos = match.index;
+ } else {
+ stream.skipToEnd();
+ }
+ }};
+ }
+
+ function SearchState() {
+ this.posFrom = this.posTo = this.lastQuery = this.query = null;
+ this.overlay = null;
+ }
+
+ function getSearchState(cm) {
+ return cm.state.search || (cm.state.search = new SearchState());
+ }
+
+ function queryCaseInsensitive(query) {
+ return typeof query == "string" && query == query.toLowerCase();
+ }
+
+ function getSearchCursor(cm, query, pos) {
+ // Heuristic: if the query string is all lowercase, do a case insensitive search.
+ return cm.getSearchCursor(query, pos, {caseFold: queryCaseInsensitive(query), multiline: true});
+ }
+
+ function persistentDialog(cm, text, deflt, onEnter, onKeyDown) {
+ cm.openDialog(text, onEnter, {
+ value: deflt,
+ selectValueOnOpen: true,
+ closeOnEnter: false,
+ onClose: function() { clearSearch(cm); },
+ onKeyDown: onKeyDown
+ });
+ }
+
+ function dialog(cm, text, shortText, deflt, f) {
+ if (cm.openDialog) cm.openDialog(text, f, {value: deflt, selectValueOnOpen: true});
+ else f(prompt(shortText, deflt));
+ }
+
+ function confirmDialog(cm, text, shortText, fs) {
+ if (cm.openConfirm) cm.openConfirm(text, fs);
+ else if (confirm(shortText)) fs[0]();
+ }
+
+ function parseString(string) {
+ return string.replace(/\\([nrt\\])/g, function(match, ch) {
+ if (ch == "n") return "\n"
+ if (ch == "r") return "\r"
+ if (ch == "t") return "\t"
+ if (ch == "\\") return "\\"
+ return match
+ })
+ }
+
+ function parseQuery(query) {
+ var isRE = query.match(/^\/(.*)\/([a-z]*)$/);
+ if (isRE) {
+ try { query = new RegExp(isRE[1], isRE[2].indexOf("i") == -1 ? "" : "i"); }
+ catch(e) {} // Not a regular expression after all, do a string search
+ } else {
+ query = parseString(query)
+ }
+ if (typeof query == "string" ? query == "" : query.test(""))
+ query = /x^/;
+ return query;
+ }
+
+ var queryDialog;
+
+ function startSearch(cm, state, query) {
+ state.queryText = query;
+ state.query = parseQuery(query);
+ cm.removeOverlay(state.overlay, queryCaseInsensitive(state.query));
+ state.overlay = searchOverlay(state.query, queryCaseInsensitive(state.query));
+ cm.addOverlay(state.overlay);
+ if (cm.showMatchesOnScrollbar) {
+ if (state.annotate) { state.annotate.clear(); state.annotate = null; }
+ state.annotate = cm.showMatchesOnScrollbar(state.query, queryCaseInsensitive(state.query));
+ }
+ }
+
+ function doSearch(cm, rev, persistent, immediate) {
+ if (!queryDialog) {
+ let doc = cm.getWrapperElement().ownerDocument;
+ let inp = doc.createElement("input");
+
+ inp.type = "search";
+ inp.placeholder = cm.l10n("findCmd.promptMessage");
+ inp.style.marginInlineStart = "1em";
+ inp.style.marginInlineEnd = "1em";
+ inp.style.flexGrow = "1";
+ inp.addEventListener("focus", () => inp.select());
+
+ queryDialog = doc.createElement("div");
+ queryDialog.appendChild(inp);
+ queryDialog.style.display = "flex";
+ }
+
+ var state = getSearchState(cm);
+ if (state.query) return findNext(cm, rev);
+ var q = cm.getSelection() || state.lastQuery;
+ if (q instanceof RegExp && q.source == "x^") q = null
+ if (persistent && cm.openDialog) {
+ var hiding = null
+ var searchNext = function(query, event) {
+ CodeMirror.e_stop(event);
+ if (!query) return;
+ if (query != state.queryText) {
+ startSearch(cm, state, query);
+ state.posFrom = state.posTo = cm.getCursor();
+ }
+ if (hiding) hiding.style.opacity = 1
+ findNext(cm, event.shiftKey, function(_, to) {
+ var dialog
+ if (to.line < 3 && document.querySelector &&
+ (dialog = cm.display.wrapper.querySelector(".CodeMirror-dialog")) &&
+ dialog.getBoundingClientRect().bottom - 4 > cm.cursorCoords(to, "window").top)
+ (hiding = dialog).style.opacity = .4
+ })
+ };
+ persistentDialog(cm, queryDialog, q, searchNext, function(event, query) {
+ var keyName = CodeMirror.keyName(event)
+ var extra = cm.getOption('extraKeys'), cmd = (extra && extra[keyName]) || CodeMirror.keyMap[cm.getOption("keyMap")][keyName]
+ if (cmd == "findNext" || cmd == "findPrev" ||
+ cmd == "findPersistentNext" || cmd == "findPersistentPrev") {
+ CodeMirror.e_stop(event);
+ startSearch(cm, getSearchState(cm), query);
+ cm.execCommand(cmd);
+ } else if (cmd == "find" || cmd == "findPersistent") {
+ CodeMirror.e_stop(event);
+ searchNext(query, event);
+ }
+ });
+ if (immediate && q) {
+ startSearch(cm, state, q);
+ findNext(cm, rev);
+ }
+ } else {
+ dialog(cm, queryDialog, "Search for:", q, function(query) {
+ if (query && !state.query) cm.operation(function() {
+ startSearch(cm, state, query);
+ state.posFrom = state.posTo = cm.getCursor();
+ findNext(cm, rev);
+ });
+ });
+ }
+ }
+
+ function findNext(cm, rev, callback) {cm.operation(function() {
+ var state = getSearchState(cm);
+ var cursor = getSearchCursor(cm, state.query, rev ? state.posFrom : state.posTo);
+ if (!cursor.find(rev)) {
+ cursor = getSearchCursor(cm, state.query, rev ? CodeMirror.Pos(cm.lastLine()) : CodeMirror.Pos(cm.firstLine(), 0));
+ if (!cursor.find(rev)) return;
+ }
+ cm.setSelection(cursor.from(), cursor.to());
+ cm.scrollIntoView({from: cursor.from(), to: cursor.to()}, 20);
+ state.posFrom = cursor.from(); state.posTo = cursor.to();
+ if (callback) callback(cursor.from(), cursor.to())
+ });}
+
+ function clearSearch(cm) {cm.operation(function() {
+ var state = getSearchState(cm);
+ state.lastQuery = state.query;
+ if (!state.query) return;
+ state.query = state.queryText = null;
+ cm.removeOverlay(state.overlay);
+ if (state.annotate) { state.annotate.clear(); state.annotate = null; }
+ });}
+
+ function replaceAll(cm, query, text) {
+ cm.operation(function() {
+ for (var cursor = getSearchCursor(cm, query); cursor.findNext();) {
+ if (typeof query != "string") {
+ var match = cm.getRange(cursor.from(), cursor.to()).match(query);
+ cursor.replace(text.replace(/\$(\d)/g, function(_, i) {return match[i];}));
+ } else cursor.replace(text);
+ }
+ });
+ }
+
+ function replace(cm, all) {
+ if (cm.getOption("readOnly")) return;
+ var query = cm.getSelection() || getSearchState(cm).lastQuery;
+
+ let doc = cm.getWrapperElement().ownerDocument;
+
+ // `searchLabel` is used as part of `replaceQueryFragment` and as a separate
+ // argument by itself, so it should be cloned.
+ let searchLabel = doc.createElement("span");
+ searchLabel.classList.add("CodeMirror-search-label");
+ searchLabel.textContent = all ? "Replace all:" : "Replace:";
+
+ let replaceQueryFragment = doc.createDocumentFragment();
+ replaceQueryFragment.appendChild(searchLabel.cloneNode(true));
+
+ let searchField = doc.createElement("input");
+ searchField.setAttribute("type", "text");
+ searchField.setAttribute("style", "width: 10em");
+ searchField.classList.add("CodeMirror-search-field");
+ replaceQueryFragment.appendChild(searchField);
+
+ let searchHint = doc.createElement("span");
+ searchHint.setAttribute("style", "color: #888");
+ searchHint.classList.add("CodeMirror-search-hint");
+ searchHint.textContent = "(Use /re/ syntax for regexp search)";
+ replaceQueryFragment.appendChild(searchHint);
+
+ dialog(cm, replaceQueryFragment, searchLabel, query, function(query) {
+ if (!query) return;
+ query = parseQuery(query);
+
+ let replacementQueryFragment = doc.createDocumentFragment();
+
+ let replaceWithLabel = searchLabel.cloneNode(false);
+ replaceWithLabel.textContent = "With:";
+ replacementQueryFragment.appendChild(replaceWithLabel);
+
+ let replaceField = doc.createElement("input");
+ replaceField.setAttribute("type", "text");
+ replaceField.setAttribute("style", "width: 10em");
+ replaceField.classList.add("CodeMirror-search-field");
+ replacementQueryFragment.appendChild(replaceField);
+
+ dialog(cm, replacementQueryFragment, "Replace with:", "", function(text) {
+ text = parseString(text)
+ if (all) {
+ replaceAll(cm, query, text)
+ } else {
+ clearSearch(cm);
+ var cursor = getSearchCursor(cm, query, cm.getCursor("from"));
+ var advance = function() {
+ var start = cursor.from(), match;
+ if (!(match = cursor.findNext())) {
+ cursor = getSearchCursor(cm, query);
+ if (!(match = cursor.findNext()) ||
+ (start && cursor.from().line == start.line && cursor.from().ch == start.ch)) return;
+ }
+ cm.setSelection(cursor.from(), cursor.to());
+ cm.scrollIntoView({ from: cursor.from(), to: cursor.to() });
+
+ let replaceConfirmFragment = doc.createDocumentFragment();
+
+ let replaceConfirmLabel = searchLabel.cloneNode(false);
+ replaceConfirmLabel.textContent = "Replace?";
+ replaceConfirmFragment.appendChild(replaceConfirmLabel);
+
+ let yesButton = doc.createElement("button");
+ yesButton.textContent = "Yes";
+ replaceConfirmFragment.appendChild(yesButton);
+
+ let noButton = doc.createElement("button");
+ noButton.textContent = "No";
+ replaceConfirmFragment.appendChild(noButton);
+
+ let allButton = doc.createElement("button");
+ allButton.textContent = "All";
+ replaceConfirmFragment.appendChild(allButton);
+
+ let stopButton = doc.createElement("button");
+ stopButton.textContent = "Stop";
+ replaceConfirmFragment.appendChild(stopButton);
+
+ confirmDialog(cm, replaceConfirmFragment, "Replace?",
+ [function() {doReplace(match);}, advance,
+ function() {replaceAll(cm, query, text)}]);
+ };
+ var doReplace = function(match) {
+ cursor.replace(typeof query == "string" ? text :
+ text.replace(/\$(\d)/g, function(_, i) {return match[i];}));
+ advance();
+ };
+ advance();
+ }
+ });
+ });
+ }
+
+ CodeMirror.commands.find = function(cm) {clearSearch(cm); doSearch(cm);};
+ CodeMirror.commands.findPersistent = function(cm) {clearSearch(cm); doSearch(cm, false, true);};
+ CodeMirror.commands.findPersistentNext = function(cm) {doSearch(cm, false, true, true);};
+ CodeMirror.commands.findPersistentPrev = function(cm) {doSearch(cm, true, true, true);};
+ CodeMirror.commands.findNext = doSearch;
+ CodeMirror.commands.findPrev = function(cm) {doSearch(cm, true);};
+ CodeMirror.commands.clearSearch = clearSearch;
+ CodeMirror.commands.replace = replace;
+ CodeMirror.commands.replaceAll = function(cm) {replace(cm, true);};
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/search/searchcursor.js b/devtools/client/shared/sourceeditor/codemirror/addon/search/searchcursor.js
new file mode 100644
index 0000000000..50dea70c83
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/search/searchcursor.js
@@ -0,0 +1,293 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"))
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod)
+ else // Plain browser env
+ mod(CodeMirror)
+})(function(CodeMirror) {
+ "use strict"
+ var Pos = CodeMirror.Pos
+
+ function regexpFlags(regexp) {
+ var flags = regexp.flags
+ return flags != null ? flags : (regexp.ignoreCase ? "i" : "")
+ + (regexp.global ? "g" : "")
+ + (regexp.multiline ? "m" : "")
+ }
+
+ function ensureFlags(regexp, flags) {
+ var current = regexpFlags(regexp), target = current
+ for (var i = 0; i < flags.length; i++) if (target.indexOf(flags.charAt(i)) == -1)
+ target += flags.charAt(i)
+ return current == target ? regexp : new RegExp(regexp.source, target)
+ }
+
+ function maybeMultiline(regexp) {
+ return /\\s|\\n|\n|\\W|\\D|\[\^/.test(regexp.source)
+ }
+
+ function searchRegexpForward(doc, regexp, start) {
+ regexp = ensureFlags(regexp, "g")
+ for (var line = start.line, ch = start.ch, last = doc.lastLine(); line <= last; line++, ch = 0) {
+ regexp.lastIndex = ch
+ var string = doc.getLine(line), match = regexp.exec(string)
+ if (match)
+ return {from: Pos(line, match.index),
+ to: Pos(line, match.index + match[0].length),
+ match: match}
+ }
+ }
+
+ function searchRegexpForwardMultiline(doc, regexp, start) {
+ if (!maybeMultiline(regexp)) return searchRegexpForward(doc, regexp, start)
+
+ regexp = ensureFlags(regexp, "gm")
+ var string, chunk = 1
+ for (var line = start.line, last = doc.lastLine(); line <= last;) {
+ // This grows the search buffer in exponentially-sized chunks
+ // between matches, so that nearby matches are fast and don't
+ // require concatenating the whole document (in case we're
+ // searching for something that has tons of matches), but at the
+ // same time, the amount of retries is limited.
+ for (var i = 0; i < chunk; i++) {
+ if (line > last) break
+ var curLine = doc.getLine(line++)
+ string = string == null ? curLine : string + "\n" + curLine
+ }
+ chunk = chunk * 2
+ regexp.lastIndex = start.ch
+ var match = regexp.exec(string)
+ if (match) {
+ var before = string.slice(0, match.index).split("\n"), inside = match[0].split("\n")
+ var startLine = start.line + before.length - 1, startCh = before[before.length - 1].length
+ return {from: Pos(startLine, startCh),
+ to: Pos(startLine + inside.length - 1,
+ inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length),
+ match: match}
+ }
+ }
+ }
+
+ function lastMatchIn(string, regexp) {
+ var cutOff = 0, match
+ for (;;) {
+ regexp.lastIndex = cutOff
+ var newMatch = regexp.exec(string)
+ if (!newMatch) return match
+ match = newMatch
+ cutOff = match.index + (match[0].length || 1)
+ if (cutOff == string.length) return match
+ }
+ }
+
+ function searchRegexpBackward(doc, regexp, start) {
+ regexp = ensureFlags(regexp, "g")
+ for (var line = start.line, ch = start.ch, first = doc.firstLine(); line >= first; line--, ch = -1) {
+ var string = doc.getLine(line)
+ if (ch > -1) string = string.slice(0, ch)
+ var match = lastMatchIn(string, regexp)
+ if (match)
+ return {from: Pos(line, match.index),
+ to: Pos(line, match.index + match[0].length),
+ match: match}
+ }
+ }
+
+ function searchRegexpBackwardMultiline(doc, regexp, start) {
+ regexp = ensureFlags(regexp, "gm")
+ var string, chunk = 1
+ for (var line = start.line, first = doc.firstLine(); line >= first;) {
+ for (var i = 0; i < chunk; i++) {
+ var curLine = doc.getLine(line--)
+ string = string == null ? curLine.slice(0, start.ch) : curLine + "\n" + string
+ }
+ chunk *= 2
+
+ var match = lastMatchIn(string, regexp)
+ if (match) {
+ var before = string.slice(0, match.index).split("\n"), inside = match[0].split("\n")
+ var startLine = line + before.length, startCh = before[before.length - 1].length
+ return {from: Pos(startLine, startCh),
+ to: Pos(startLine + inside.length - 1,
+ inside.length == 1 ? startCh + inside[0].length : inside[inside.length - 1].length),
+ match: match}
+ }
+ }
+ }
+
+ var doFold, noFold
+ if (String.prototype.normalize) {
+ doFold = function(str) { return str.normalize("NFD").toLowerCase() }
+ noFold = function(str) { return str.normalize("NFD") }
+ } else {
+ doFold = function(str) { return str.toLowerCase() }
+ noFold = function(str) { return str }
+ }
+
+ // Maps a position in a case-folded line back to a position in the original line
+ // (compensating for codepoints increasing in number during folding)
+ function adjustPos(orig, folded, pos, foldFunc) {
+ if (orig.length == folded.length) return pos
+ for (var min = 0, max = pos + Math.max(0, orig.length - folded.length);;) {
+ if (min == max) return min
+ var mid = (min + max) >> 1
+ var len = foldFunc(orig.slice(0, mid)).length
+ if (len == pos) return mid
+ else if (len > pos) max = mid
+ else min = mid + 1
+ }
+ }
+
+ function searchStringForward(doc, query, start, caseFold) {
+ // Empty string would match anything and never progress, so we
+ // define it to match nothing instead.
+ if (!query.length) return null
+ var fold = caseFold ? doFold : noFold
+ var lines = fold(query).split(/\r|\n\r?/)
+
+ search: for (var line = start.line, ch = start.ch, last = doc.lastLine() + 1 - lines.length; line <= last; line++, ch = 0) {
+ var orig = doc.getLine(line).slice(ch), string = fold(orig)
+ if (lines.length == 1) {
+ var found = string.indexOf(lines[0])
+ if (found == -1) continue search
+ var start = adjustPos(orig, string, found, fold) + ch
+ return {from: Pos(line, adjustPos(orig, string, found, fold) + ch),
+ to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold) + ch)}
+ } else {
+ var cutFrom = string.length - lines[0].length
+ if (string.slice(cutFrom) != lines[0]) continue search
+ for (var i = 1; i < lines.length - 1; i++)
+ if (fold(doc.getLine(line + i)) != lines[i]) continue search
+ var end = doc.getLine(line + lines.length - 1), endString = fold(end), lastLine = lines[lines.length - 1]
+ if (endString.slice(0, lastLine.length) != lastLine) continue search
+ return {from: Pos(line, adjustPos(orig, string, cutFrom, fold) + ch),
+ to: Pos(line + lines.length - 1, adjustPos(end, endString, lastLine.length, fold))}
+ }
+ }
+ }
+
+ function searchStringBackward(doc, query, start, caseFold) {
+ if (!query.length) return null
+ var fold = caseFold ? doFold : noFold
+ var lines = fold(query).split(/\r|\n\r?/)
+
+ search: for (var line = start.line, ch = start.ch, first = doc.firstLine() - 1 + lines.length; line >= first; line--, ch = -1) {
+ var orig = doc.getLine(line)
+ if (ch > -1) orig = orig.slice(0, ch)
+ var string = fold(orig)
+ if (lines.length == 1) {
+ var found = string.lastIndexOf(lines[0])
+ if (found == -1) continue search
+ return {from: Pos(line, adjustPos(orig, string, found, fold)),
+ to: Pos(line, adjustPos(orig, string, found + lines[0].length, fold))}
+ } else {
+ var lastLine = lines[lines.length - 1]
+ if (string.slice(0, lastLine.length) != lastLine) continue search
+ for (var i = 1, start = line - lines.length + 1; i < lines.length - 1; i++)
+ if (fold(doc.getLine(start + i)) != lines[i]) continue search
+ var top = doc.getLine(line + 1 - lines.length), topString = fold(top)
+ if (topString.slice(topString.length - lines[0].length) != lines[0]) continue search
+ return {from: Pos(line + 1 - lines.length, adjustPos(top, topString, top.length - lines[0].length, fold)),
+ to: Pos(line, adjustPos(orig, string, lastLine.length, fold))}
+ }
+ }
+ }
+
+ function SearchCursor(doc, query, pos, options) {
+ this.atOccurrence = false
+ this.doc = doc
+ pos = pos ? doc.clipPos(pos) : Pos(0, 0)
+ this.pos = {from: pos, to: pos}
+
+ var caseFold
+ if (typeof options == "object") {
+ caseFold = options.caseFold
+ } else { // Backwards compat for when caseFold was the 4th argument
+ caseFold = options
+ options = null
+ }
+
+ if (typeof query == "string") {
+ if (caseFold == null) caseFold = false
+ this.matches = function(reverse, pos) {
+ return (reverse ? searchStringBackward : searchStringForward)(doc, query, pos, caseFold)
+ }
+ } else {
+ query = ensureFlags(query, "gm")
+ if (!options || options.multiline !== false)
+ this.matches = function(reverse, pos) {
+ return (reverse ? searchRegexpBackwardMultiline : searchRegexpForwardMultiline)(doc, query, pos)
+ }
+ else
+ this.matches = function(reverse, pos) {
+ return (reverse ? searchRegexpBackward : searchRegexpForward)(doc, query, pos)
+ }
+ }
+ }
+
+ SearchCursor.prototype = {
+ findNext: function() {return this.find(false)},
+ findPrevious: function() {return this.find(true)},
+
+ find: function(reverse) {
+ var result = this.matches(reverse, this.doc.clipPos(reverse ? this.pos.from : this.pos.to))
+
+ // Implements weird auto-growing behavior on null-matches for
+ // backwards-compatiblity with the vim code (unfortunately)
+ while (result && CodeMirror.cmpPos(result.from, result.to) == 0) {
+ if (reverse) {
+ if (result.from.ch) result.from = Pos(result.from.line, result.from.ch - 1)
+ else if (result.from.line == this.doc.firstLine()) result = null
+ else result = this.matches(reverse, this.doc.clipPos(Pos(result.from.line - 1)))
+ } else {
+ if (result.to.ch < this.doc.getLine(result.to.line).length) result.to = Pos(result.to.line, result.to.ch + 1)
+ else if (result.to.line == this.doc.lastLine()) result = null
+ else result = this.matches(reverse, Pos(result.to.line + 1, 0))
+ }
+ }
+
+ if (result) {
+ this.pos = result
+ this.atOccurrence = true
+ return this.pos.match || true
+ } else {
+ var end = Pos(reverse ? this.doc.firstLine() : this.doc.lastLine() + 1, 0)
+ this.pos = {from: end, to: end}
+ return this.atOccurrence = false
+ }
+ },
+
+ from: function() {if (this.atOccurrence) return this.pos.from},
+ to: function() {if (this.atOccurrence) return this.pos.to},
+
+ replace: function(newText, origin) {
+ if (!this.atOccurrence) return
+ var lines = CodeMirror.splitLines(newText)
+ this.doc.replaceRange(lines, this.pos.from, this.pos.to, origin)
+ this.pos.to = Pos(this.pos.from.line + lines.length - 1,
+ lines[lines.length - 1].length + (lines.length == 1 ? this.pos.from.ch : 0))
+ }
+ }
+
+ CodeMirror.defineExtension("getSearchCursor", function(query, pos, caseFold) {
+ return new SearchCursor(this.doc, query, pos, caseFold)
+ })
+ CodeMirror.defineDocExtension("getSearchCursor", function(query, pos, caseFold) {
+ return new SearchCursor(this, query, pos, caseFold)
+ })
+
+ CodeMirror.defineExtension("selectMatches", function(query, caseFold) {
+ var ranges = []
+ var cur = this.getSearchCursor(query, this.getCursor("from"), caseFold)
+ while (cur.findNext()) {
+ if (CodeMirror.cmpPos(cur.to(), this.getCursor("to")) > 0) break
+ ranges.push({anchor: cur.from(), head: cur.to()})
+ }
+ if (ranges.length)
+ this.setSelections(ranges, 0)
+ })
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/selection/active-line.js b/devtools/client/shared/sourceeditor/codemirror/addon/selection/active-line.js
new file mode 100644
index 0000000000..1bf6f97559
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/selection/active-line.js
@@ -0,0 +1,72 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+ var WRAP_CLASS = "CodeMirror-activeline";
+ var BACK_CLASS = "CodeMirror-activeline-background";
+ var GUTT_CLASS = "CodeMirror-activeline-gutter";
+
+ CodeMirror.defineOption("styleActiveLine", false, function(cm, val, old) {
+ var prev = old == CodeMirror.Init ? false : old;
+ if (val == prev) return
+ if (prev) {
+ cm.off("beforeSelectionChange", selectionChange);
+ clearActiveLines(cm);
+ delete cm.state.activeLines;
+ }
+ if (val) {
+ cm.state.activeLines = [];
+ updateActiveLines(cm, cm.listSelections());
+ cm.on("beforeSelectionChange", selectionChange);
+ }
+ });
+
+ function clearActiveLines(cm) {
+ for (var i = 0; i < cm.state.activeLines.length; i++) {
+ cm.removeLineClass(cm.state.activeLines[i], "wrap", WRAP_CLASS);
+ cm.removeLineClass(cm.state.activeLines[i], "background", BACK_CLASS);
+ cm.removeLineClass(cm.state.activeLines[i], "gutter", GUTT_CLASS);
+ }
+ }
+
+ function sameArray(a, b) {
+ if (a.length != b.length) return false;
+ for (var i = 0; i < a.length; i++)
+ if (a[i] != b[i]) return false;
+ return true;
+ }
+
+ function updateActiveLines(cm, ranges) {
+ var active = [];
+ for (var i = 0; i < ranges.length; i++) {
+ var range = ranges[i];
+ var option = cm.getOption("styleActiveLine");
+ if (typeof option == "object" && option.nonEmpty ? range.anchor.line != range.head.line : !range.empty())
+ continue
+ var line = cm.getLineHandleVisualStart(range.head.line);
+ if (active[active.length - 1] != line) active.push(line);
+ }
+ if (sameArray(cm.state.activeLines, active)) return;
+ cm.operation(function() {
+ clearActiveLines(cm);
+ for (var i = 0; i < active.length; i++) {
+ cm.addLineClass(active[i], "wrap", WRAP_CLASS);
+ cm.addLineClass(active[i], "background", BACK_CLASS);
+ cm.addLineClass(active[i], "gutter", GUTT_CLASS);
+ }
+ cm.state.activeLines = active;
+ });
+ }
+
+ function selectionChange(cm, sel) {
+ updateActiveLines(cm, sel.ranges);
+ }
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/addon/selection/mark-selection.js b/devtools/client/shared/sourceeditor/codemirror/addon/selection/mark-selection.js
new file mode 100644
index 0000000000..d838723b48
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/addon/selection/mark-selection.js
@@ -0,0 +1,119 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+// Because sometimes you need to mark the selected *text*.
+//
+// Adds an option 'styleSelectedText' which, when enabled, gives
+// selected text the CSS class given as option value, or
+// "CodeMirror-selectedtext" when the value is not a string.
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ CodeMirror.defineOption("styleSelectedText", false, function(cm, val, old) {
+ var prev = old && old != CodeMirror.Init;
+ if (val && !prev) {
+ cm.state.markedSelection = [];
+ cm.state.markedSelectionStyle = typeof val == "string" ? val : "CodeMirror-selectedtext";
+ reset(cm);
+ cm.on("cursorActivity", onCursorActivity);
+ cm.on("change", onChange);
+ } else if (!val && prev) {
+ cm.off("cursorActivity", onCursorActivity);
+ cm.off("change", onChange);
+ clear(cm);
+ cm.state.markedSelection = cm.state.markedSelectionStyle = null;
+ }
+ });
+
+ function onCursorActivity(cm) {
+ if (cm.state.markedSelection)
+ cm.operation(function() { update(cm); });
+ }
+
+ function onChange(cm) {
+ if (cm.state.markedSelection && cm.state.markedSelection.length)
+ cm.operation(function() { clear(cm); });
+ }
+
+ var CHUNK_SIZE = 8;
+ var Pos = CodeMirror.Pos;
+ var cmp = CodeMirror.cmpPos;
+
+ function coverRange(cm, from, to, addAt) {
+ if (cmp(from, to) == 0) return;
+ var array = cm.state.markedSelection;
+ var cls = cm.state.markedSelectionStyle;
+ for (var line = from.line;;) {
+ var start = line == from.line ? from : Pos(line, 0);
+ var endLine = line + CHUNK_SIZE, atEnd = endLine >= to.line;
+ var end = atEnd ? to : Pos(endLine, 0);
+ var mark = cm.markText(start, end, {className: cls});
+ if (addAt == null) array.push(mark);
+ else array.splice(addAt++, 0, mark);
+ if (atEnd) break;
+ line = endLine;
+ }
+ }
+
+ function clear(cm) {
+ var array = cm.state.markedSelection;
+ for (var i = 0; i < array.length; ++i) array[i].clear();
+ array.length = 0;
+ }
+
+ function reset(cm) {
+ clear(cm);
+ var ranges = cm.listSelections();
+ for (var i = 0; i < ranges.length; i++)
+ coverRange(cm, ranges[i].from(), ranges[i].to());
+ }
+
+ function update(cm) {
+ if (!cm.somethingSelected()) return clear(cm);
+ if (cm.listSelections().length > 1) return reset(cm);
+
+ var from = cm.getCursor("start"), to = cm.getCursor("end");
+
+ var array = cm.state.markedSelection;
+ if (!array.length) return coverRange(cm, from, to);
+
+ var coverStart = array[0].find(), coverEnd = array[array.length - 1].find();
+ if (!coverStart || !coverEnd || to.line - from.line <= CHUNK_SIZE ||
+ cmp(from, coverEnd.to) >= 0 || cmp(to, coverStart.from) <= 0)
+ return reset(cm);
+
+ while (cmp(from, coverStart.from) > 0) {
+ array.shift().clear();
+ coverStart = array[0].find();
+ }
+ if (cmp(from, coverStart.from) < 0) {
+ if (coverStart.to.line - from.line < CHUNK_SIZE) {
+ array.shift().clear();
+ coverRange(cm, from, coverStart.to, 0);
+ } else {
+ coverRange(cm, from, coverStart.from, 0);
+ }
+ }
+
+ while (cmp(to, coverEnd.to) < 0) {
+ array.pop().clear();
+ coverEnd = array[array.length - 1].find();
+ }
+ if (cmp(to, coverEnd.to) > 0) {
+ if (to.line - coverEnd.from.line < CHUNK_SIZE) {
+ array.pop().clear();
+ coverRange(cm, coverEnd.from, to);
+ } else {
+ coverRange(cm, coverEnd.to, to);
+ }
+ }
+ }
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/cmiframe.html b/devtools/client/shared/sourceeditor/codemirror/cmiframe.html
new file mode 100644
index 0000000000..85bcfe5a94
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/cmiframe.html
@@ -0,0 +1,28 @@
+<!DOCTYPE html>
+<html dir='ltr'>
+<head>
+ <meta charset="utf-8">
+ <meta name="color-scheme" content="light dark">
+ <style id="cmBaseStyle">
+ html, body { height: 100%; }
+ body { margin: 0; overflow: hidden; }
+ .CodeMirror {
+ width: 100% !important;
+ /*
+ 1. Use fallback values for CSS variables, so that the text is sized
+ correctly while all the stylesheets load. Fallback values should
+ match the values in devtools/client/themes/variables.css
+ 2. Avoid !important for the font-size, to let CodeMirror set its own
+ font-size based on prefs.
+ */
+ font-size: var(--theme-code-font-size, 11px);
+ line-height: var(--theme-code-line-height, 1.3636) !important;
+ }
+ </style>
+ <link rel='stylesheet' href="chrome://devtools/content/shared/sourceeditor/codemirror/lib/codemirror.css">
+ <link rel='stylesheet' href="chrome://devtools/content/shared/sourceeditor/codemirror/addon/dialog/dialog.css">
+ <link rel='stylesheet' href="chrome://devtools/content/shared/sourceeditor/codemirror/mozilla.css">
+ <script src="chrome://devtools/content/shared/theme-switching.js"></script>
+</head>
+<body class='theme-body devtools-monospace'></body>
+</html>
diff --git a/devtools/client/shared/sourceeditor/codemirror/codemirror.bundle.js b/devtools/client/shared/sourceeditor/codemirror/codemirror.bundle.js
new file mode 100644
index 0000000000..28a7c5fad4
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/codemirror.bundle.js
@@ -0,0 +1 @@
+var CodeMirror=function(e){var t={};function n(r){if(t[r])return t[r].exports;var i=t[r]={i:r,l:!1,exports:{}};return e[r].call(i.exports,i,i.exports,n),i.l=!0,i.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var i in e)n.d(r,i,function(t){return e[t]}.bind(null,i));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=7)}([function(e,t,n){e.exports=function(){"use strict";var e=navigator.userAgent,t=navigator.platform,n=/gecko\/\d/i.test(e),r=/MSIE \d/.test(e),i=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(e),o=/Edge\/(\d+)/.exec(e),a=r||i||o,l=a&&(r?document.documentMode||6:+(o||i)[1]),s=!o&&/WebKit\//.test(e),c=s&&/Qt\/\d+\.\d+/.test(e),u=!o&&/Chrome\//.test(e),f=/Opera\//.test(e),d=/Apple Computer/.test(navigator.vendor),h=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(e),p=/PhantomJS/.test(e),m=!o&&/AppleWebKit/.test(e)&&/Mobile\/\w+/.test(e),g=/Android/.test(e),v=m||g||/webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(e),y=m||/Mac/.test(t),b=/\bCrOS\b/.test(e),x=/win/i.test(t),w=f&&e.match(/Version\/(\d*\.\d*)/);w&&(w=Number(w[1])),w&&w>=15&&(f=!1,s=!0);var k=y&&(c||f&&(null==w||w<12.11)),C=n||a&&l>=9;function S(e){return new RegExp("(^|\\s)"+e+"(?:$|\\s)\\s*")}var T,L=function(e,t){var n=e.className,r=S(t).exec(n);if(r){var i=n.slice(r.index+r[0].length);e.className=n.slice(0,r.index)+(i?r[1]+i:"")}};function M(e){for(var t=e.childNodes.length;t>0;--t)e.removeChild(e.firstChild);return e}function O(e,t){return M(e).appendChild(t)}function N(e,t,n,r){var i=document.createElement(e);if(n&&(i.className=n),r&&(i.style.cssText=r),"string"==typeof t)i.appendChild(document.createTextNode(t));else if(t)for(var o=0;o<t.length;++o)i.appendChild(t[o]);return i}function A(e,t,n,r){var i=N(e,t,n,r);return i.setAttribute("role","presentation"),i}function E(e,t){if(3==t.nodeType&&(t=t.parentNode),e.contains)return e.contains(t);do{if(11==t.nodeType&&(t=t.host),t==e)return!0}while(t=t.parentNode)}function z(){var e;try{e=document.activeElement}catch(t){e=document.body||null}for(;e&&e.shadowRoot&&e.shadowRoot.activeElement;)e=e.shadowRoot.activeElement;return e}function P(e,t){var n=e.className;S(t).test(n)||(e.className+=(n?" ":"")+t)}function D(e,t){for(var n=e.split(" "),r=0;r<n.length;r++)n[r]&&!S(n[r]).test(t)&&(t+=" "+n[r]);return t}T=document.createRange?function(e,t,n,r){var i=document.createRange();return i.setEnd(r||e,n),i.setStart(e,t),i}:function(e,t,n){var r=document.body.createTextRange();try{r.moveToElementText(e.parentNode)}catch(e){return r}return r.collapse(!0),r.moveEnd("character",n),r.moveStart("character",t),r};var I=function(e){e.select()};function F(e){var t=Array.prototype.slice.call(arguments,1);return function(){return e.apply(null,t)}}function _(e,t,n){for(var r in t||(t={}),e)!e.hasOwnProperty(r)||!1===n&&t.hasOwnProperty(r)||(t[r]=e[r]);return t}function W(e,t,n,r,i){null==t&&-1==(t=e.search(/[^\s\u00a0]/))&&(t=e.length);for(var o=r||0,a=i||0;;){var l=e.indexOf("\t",o);if(l<0||l>=t)return a+(t-o);a+=l-o,a+=n-a%n,o=l+1}}m?I=function(e){e.selectionStart=0,e.selectionEnd=e.value.length}:a&&(I=function(e){try{e.select()}catch(e){}});var H=function(){this.id=null,this.f=null,this.time=0,this.handler=F(this.onTimeout,this)};function R(e,t){for(var n=0;n<e.length;++n)if(e[n]==t)return n;return-1}H.prototype.onTimeout=function(e){e.id=0,e.time<=+new Date?e.f():setTimeout(e.handler,e.time-+new Date)},H.prototype.set=function(e,t){this.f=t;var n=+new Date+e;(!this.id||n<this.time)&&(clearTimeout(this.id),this.id=setTimeout(this.handler,e),this.time=n)};var B={toString:function(){return"CodeMirror.Pass"}},j={scroll:!1},q={origin:"*mouse"},U={origin:"+move"};function V(e,t,n){for(var r=0,i=0;;){var o=e.indexOf("\t",r);-1==o&&(o=e.length);var a=o-r;if(o==e.length||i+a>=t)return r+Math.min(a,t-i);if(i+=o-r,r=o+1,(i+=n-i%n)>=t)return r}}var K=[""];function $(e){for(;K.length<=e;)K.push(G(K)+" ");return K[e]}function G(e){return e[e.length-1]}function X(e,t){for(var n=[],r=0;r<e.length;r++)n[r]=t(e[r],r);return n}function Z(){}function Y(e,t){var n;return Object.create?n=Object.create(e):(Z.prototype=e,n=new Z),t&&_(t,n),n}var Q=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;function J(e){return/\w/.test(e)||e>"€"&&(e.toUpperCase()!=e.toLowerCase()||Q.test(e))}function ee(e,t){return t?!!(t.source.indexOf("\\w")>-1&&J(e))||t.test(e):J(e)}function te(e){for(var t in e)if(e.hasOwnProperty(t)&&e[t])return!1;return!0}var ne=/[\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 re(e){return e.charCodeAt(0)>=768&&ne.test(e)}function ie(e,t,n){for(;(n<0?t>0:t<e.length)&&re(e.charAt(t));)t+=n;return t}function oe(e,t,n){for(var r=t>n?-1:1;;){if(t==n)return t;var i=(t+n)/2,o=r<0?Math.ceil(i):Math.floor(i);if(o==t)return e(o)?t:n;e(o)?n=o:t=o+r}}var ae=null;function le(e,t,n){var r;ae=null;for(var i=0;i<e.length;++i){var o=e[i];if(o.from<t&&o.to>t)return i;o.to==t&&(o.from!=o.to&&"before"==n?r=i:ae=i),o.from==t&&(o.from!=o.to&&"before"!=n?r=i:ae=i)}return null!=r?r:ae}var se=function(){var e=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,t=/[stwN]/,n=/[LRr]/,r=/[Lb1n]/,i=/[1n]/;function o(e,t,n){this.level=e,this.from=t,this.to=n}return function(a,l){var s="ltr"==l?"L":"R";if(0==a.length||"ltr"==l&&!e.test(a))return!1;for(var c,u=a.length,f=[],d=0;d<u;++d)f.push((c=a.charCodeAt(d))<=247?"bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN".charAt(c):1424<=c&&c<=1524?"R":1536<=c&&c<=1785?"nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111".charAt(c-1536):1774<=c&&c<=2220?"r":8192<=c&&c<=8203?"w":8204==c?"b":"L");for(var h=0,p=s;h<u;++h){var m=f[h];"m"==m?f[h]=p:p=m}for(var g=0,v=s;g<u;++g){var y=f[g];"1"==y&&"r"==v?f[g]="n":n.test(y)&&(v=y,"r"==y&&(f[g]="R"))}for(var b=1,x=f[0];b<u-1;++b){var w=f[b];"+"==w&&"1"==x&&"1"==f[b+1]?f[b]="1":","!=w||x!=f[b+1]||"1"!=x&&"n"!=x||(f[b]=x),x=w}for(var k=0;k<u;++k){var C=f[k];if(","==C)f[k]="N";else if("%"==C){var S=void 0;for(S=k+1;S<u&&"%"==f[S];++S);for(var T=k&&"!"==f[k-1]||S<u&&"1"==f[S]?"1":"N",L=k;L<S;++L)f[L]=T;k=S-1}}for(var M=0,O=s;M<u;++M){var N=f[M];"L"==O&&"1"==N?f[M]="L":n.test(N)&&(O=N)}for(var A=0;A<u;++A)if(t.test(f[A])){var E=void 0;for(E=A+1;E<u&&t.test(f[E]);++E);for(var z="L"==(A?f[A-1]:s),P=z==("L"==(E<u?f[E]:s))?z?"L":"R":s,D=A;D<E;++D)f[D]=P;A=E-1}for(var I,F=[],_=0;_<u;)if(r.test(f[_])){var W=_;for(++_;_<u&&r.test(f[_]);++_);F.push(new o(0,W,_))}else{var H=_,R=F.length,B="rtl"==l?1:0;for(++_;_<u&&"L"!=f[_];++_);for(var j=H;j<_;)if(i.test(f[j])){H<j&&(F.splice(R,0,new o(1,H,j)),R+=B);var q=j;for(++j;j<_&&i.test(f[j]);++j);F.splice(R,0,new o(2,q,j)),R+=B,H=j}else++j;H<_&&F.splice(R,0,new o(1,H,_))}return"ltr"==l&&(1==F[0].level&&(I=a.match(/^\s+/))&&(F[0].from=I[0].length,F.unshift(new o(0,0,I[0].length))),1==G(F).level&&(I=a.match(/\s+$/))&&(G(F).to-=I[0].length,F.push(new o(0,u-I[0].length,u)))),"rtl"==l?F.reverse():F}}();function ce(e,t){var n=e.order;return null==n&&(n=e.order=se(e.text,t)),n}var ue=[],fe=function(e,t,n){if(e.addEventListener)e.addEventListener(t,n,!1);else if(e.attachEvent)e.attachEvent("on"+t,n);else{var r=e._handlers||(e._handlers={});r[t]=(r[t]||ue).concat(n)}};function de(e,t){return e._handlers&&e._handlers[t]||ue}function he(e,t,n){if(e.removeEventListener)e.removeEventListener(t,n,!1);else if(e.detachEvent)e.detachEvent("on"+t,n);else{var r=e._handlers,i=r&&r[t];if(i){var o=R(i,n);o>-1&&(r[t]=i.slice(0,o).concat(i.slice(o+1)))}}}function pe(e,t){var n=de(e,t);if(n.length)for(var r=Array.prototype.slice.call(arguments,2),i=0;i<n.length;++i)n[i].apply(null,r)}function me(e,t,n){return"string"==typeof t&&(t={type:t,preventDefault:function(){this.defaultPrevented=!0}}),pe(e,n||t.type,e,t),we(t)||t.codemirrorIgnore}function ge(e){var t=e._handlers&&e._handlers.cursorActivity;if(t)for(var n=e.curOp.cursorActivityHandlers||(e.curOp.cursorActivityHandlers=[]),r=0;r<t.length;++r)-1==R(n,t[r])&&n.push(t[r])}function ve(e,t){return de(e,t).length>0}function ye(e){e.prototype.on=function(e,t){fe(this,e,t)},e.prototype.off=function(e,t){he(this,e,t)}}function be(e){e.preventDefault?e.preventDefault():e.returnValue=!1}function xe(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0}function we(e){return null!=e.defaultPrevented?e.defaultPrevented:0==e.returnValue}function ke(e){be(e),xe(e)}function Ce(e){return e.target||e.srcElement}function Se(e){var t=e.which;return null==t&&(1&e.button?t=1:2&e.button?t=3:4&e.button&&(t=2)),y&&e.ctrlKey&&1==t&&(t=3),t}var Te,Le,Me=function(){if(a&&l<9)return!1;var e=N("div");return"draggable"in e||"dragDrop"in e}();function Oe(e){if(null==Te){var t=N("span","​");O(e,N("span",[t,document.createTextNode("x")])),0!=e.firstChild.offsetHeight&&(Te=t.offsetWidth<=1&&t.offsetHeight>2&&!(a&&l<8))}var n=Te?N("span","​"):N("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px");return n.setAttribute("cm-text",""),n}function Ne(e){if(null!=Le)return Le;var t=O(e,document.createTextNode("AخA")),n=T(t,0,1).getBoundingClientRect(),r=T(t,1,2).getBoundingClientRect();return M(e),!(!n||n.left==n.right)&&(Le=r.right-n.right<3)}var Ae,Ee=3!="\n\nb".split(/\n/).length?function(e){for(var t=0,n=[],r=e.length;t<=r;){var i=e.indexOf("\n",t);-1==i&&(i=e.length);var o=e.slice(t,"\r"==e.charAt(i-1)?i-1:i),a=o.indexOf("\r");-1!=a?(n.push(o.slice(0,a)),t+=a+1):(n.push(o),t=i+1)}return n}:function(e){return e.split(/\r\n?|\n/)},ze=window.getSelection?function(e){try{return e.selectionStart!=e.selectionEnd}catch(e){return!1}}:function(e){var t;try{t=e.ownerDocument.selection.createRange()}catch(e){}return!(!t||t.parentElement()!=e)&&0!=t.compareEndPoints("StartToEnd",t)},Pe="oncopy"in(Ae=N("div"))||(Ae.setAttribute("oncopy","return;"),"function"==typeof Ae.oncopy),De=null,Ie={},Fe={};function _e(e,t){arguments.length>2&&(t.dependencies=Array.prototype.slice.call(arguments,2)),Ie[e]=t}function We(e){if("string"==typeof e&&Fe.hasOwnProperty(e))e=Fe[e];else if(e&&"string"==typeof e.name&&Fe.hasOwnProperty(e.name)){var t=Fe[e.name];"string"==typeof t&&(t={name:t}),(e=Y(t,e)).name=t.name}else{if("string"==typeof e&&/^[\w\-]+\/[\w\-]+\+xml$/.test(e))return We("application/xml");if("string"==typeof e&&/^[\w\-]+\/[\w\-]+\+json$/.test(e))return We("application/json")}return"string"==typeof e?{name:e}:e||{name:"null"}}function He(e,t){t=We(t);var n=Ie[t.name];if(!n)return He(e,"text/plain");var r=n(e,t);if(Re.hasOwnProperty(t.name)){var i=Re[t.name];for(var o in i)i.hasOwnProperty(o)&&(r.hasOwnProperty(o)&&(r["_"+o]=r[o]),r[o]=i[o])}if(r.name=t.name,t.helperType&&(r.helperType=t.helperType),t.modeProps)for(var a in t.modeProps)r[a]=t.modeProps[a];return r}var Re={};function Be(e,t){_(t,Re.hasOwnProperty(e)?Re[e]:Re[e]={})}function je(e,t){if(!0===t)return t;if(e.copyState)return e.copyState(t);var n={};for(var r in t){var i=t[r];i instanceof Array&&(i=i.concat([])),n[r]=i}return n}function qe(e,t){for(var n;e.innerMode&&(n=e.innerMode(t))&&n.mode!=e;)t=n.state,e=n.mode;return n||{mode:e,state:t}}function Ue(e,t,n){return!e.startState||e.startState(t,n)}var Ve=function(e,t,n){this.pos=this.start=0,this.string=e,this.tabSize=t||8,this.lastColumnPos=this.lastColumnValue=0,this.lineStart=0,this.lineOracle=n};function Ke(e,t){if((t-=e.first)<0||t>=e.size)throw new Error("There is no line "+(t+e.first)+" in the document.");for(var n=e;!n.lines;)for(var r=0;;++r){var i=n.children[r],o=i.chunkSize();if(t<o){n=i;break}t-=o}return n.lines[t]}function $e(e,t,n){var r=[],i=t.line;return e.iter(t.line,n.line+1,(function(e){var o=e.text;i==n.line&&(o=o.slice(0,n.ch)),i==t.line&&(o=o.slice(t.ch)),r.push(o),++i})),r}function Ge(e,t,n){var r=[];return e.iter(t,n,(function(e){r.push(e.text)})),r}function Xe(e,t){var n=t-e.height;if(n)for(var r=e;r;r=r.parent)r.height+=n}function Ze(e){if(null==e.parent)return null;for(var t=e.parent,n=R(t.lines,e),r=t.parent;r;t=r,r=r.parent)for(var i=0;r.children[i]!=t;++i)n+=r.children[i].chunkSize();return n+t.first}function Ye(e,t){var n=e.first;e:do{for(var r=0;r<e.children.length;++r){var i=e.children[r],o=i.height;if(t<o){e=i;continue e}t-=o,n+=i.chunkSize()}return n}while(!e.lines);for(var a=0;a<e.lines.length;++a){var l=e.lines[a].height;if(t<l)break;t-=l}return n+a}function Qe(e,t){return t>=e.first&&t<e.first+e.size}function Je(e,t){return String(e.lineNumberFormatter(t+e.firstLineNumber))}function et(e,t,n){if(void 0===n&&(n=null),!(this instanceof et))return new et(e,t,n);this.line=e,this.ch=t,this.sticky=n}function tt(e,t){return e.line-t.line||e.ch-t.ch}function nt(e,t){return e.sticky==t.sticky&&0==tt(e,t)}function rt(e){return et(e.line,e.ch)}function it(e,t){return tt(e,t)<0?t:e}function ot(e,t){return tt(e,t)<0?e:t}function at(e,t){return Math.max(e.first,Math.min(t,e.first+e.size-1))}function lt(e,t){if(t.line<e.first)return et(e.first,0);var n=e.first+e.size-1;return t.line>n?et(n,Ke(e,n).text.length):function(e,t){var n=e.ch;return null==n||n>t?et(e.line,t):n<0?et(e.line,0):e}(t,Ke(e,t.line).text.length)}function st(e,t){for(var n=[],r=0;r<t.length;r++)n[r]=lt(e,t[r]);return n}Ve.prototype.eol=function(){return this.pos>=this.string.length},Ve.prototype.sol=function(){return this.pos==this.lineStart},Ve.prototype.peek=function(){return this.string.charAt(this.pos)||void 0},Ve.prototype.next=function(){if(this.pos<this.string.length)return this.string.charAt(this.pos++)},Ve.prototype.eat=function(e){var t=this.string.charAt(this.pos);if("string"==typeof e?t==e:t&&(e.test?e.test(t):e(t)))return++this.pos,t},Ve.prototype.eatWhile=function(e){for(var t=this.pos;this.eat(e););return this.pos>t},Ve.prototype.eatSpace=function(){for(var e=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e},Ve.prototype.skipToEnd=function(){this.pos=this.string.length},Ve.prototype.skipTo=function(e){var t=this.string.indexOf(e,this.pos);if(t>-1)return this.pos=t,!0},Ve.prototype.backUp=function(e){this.pos-=e},Ve.prototype.column=function(){return this.lastColumnPos<this.start&&(this.lastColumnValue=W(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue),this.lastColumnPos=this.start),this.lastColumnValue-(this.lineStart?W(this.string,this.lineStart,this.tabSize):0)},Ve.prototype.indentation=function(){return W(this.string,null,this.tabSize)-(this.lineStart?W(this.string,this.lineStart,this.tabSize):0)},Ve.prototype.match=function(e,t,n){if("string"!=typeof e){var r=this.string.slice(this.pos).match(e);return r&&r.index>0?null:(r&&!1!==t&&(this.pos+=r[0].length),r)}var i=function(e){return n?e.toLowerCase():e};if(i(this.string.substr(this.pos,e.length))==i(e))return!1!==t&&(this.pos+=e.length),!0},Ve.prototype.current=function(){return this.string.slice(this.start,this.pos)},Ve.prototype.hideFirstChars=function(e,t){this.lineStart+=e;try{return t()}finally{this.lineStart-=e}},Ve.prototype.lookAhead=function(e){var t=this.lineOracle;return t&&t.lookAhead(e)},Ve.prototype.baseToken=function(){var e=this.lineOracle;return e&&e.baseToken(this.pos)};var ct=function(e,t){this.state=e,this.lookAhead=t},ut=function(e,t,n,r){this.state=t,this.doc=e,this.line=n,this.maxLookAhead=r||0,this.baseTokens=null,this.baseTokenPos=1};function ft(e,t,n,r){var i=[e.state.modeGen],o={};xt(e,t.text,e.doc.mode,n,(function(e,t){return i.push(e,t)}),o,r);for(var a=n.state,l=function(r){n.baseTokens=i;var l=e.state.overlays[r],s=1,c=0;n.state=!0,xt(e,t.text,l.mode,n,(function(e,t){for(var n=s;c<e;){var r=i[s];r>e&&i.splice(s,1,e,i[s+1],r),s+=2,c=Math.min(e,r)}if(t)if(l.opaque)i.splice(n,s-n,e,"overlay "+t),s=n+2;else for(;n<s;n+=2){var o=i[n+1];i[n+1]=(o?o+" ":"")+"overlay "+t}}),o),n.state=a,n.baseTokens=null,n.baseTokenPos=1},s=0;s<e.state.overlays.length;++s)l(s);return{styles:i,classes:o.bgClass||o.textClass?o:null}}function dt(e,t,n){if(!t.styles||t.styles[0]!=e.state.modeGen){var r=ht(e,Ze(t)),i=t.text.length>e.options.maxHighlightLength&&je(e.doc.mode,r.state),o=ft(e,t,r);i&&(r.state=i),t.stateAfter=r.save(!i),t.styles=o.styles,o.classes?t.styleClasses=o.classes:t.styleClasses&&(t.styleClasses=null),n===e.doc.highlightFrontier&&(e.doc.modeFrontier=Math.max(e.doc.modeFrontier,++e.doc.highlightFrontier))}return t.styles}function ht(e,t,n){var r=e.doc,i=e.display;if(!r.mode.startState)return new ut(r,!0,t);var o=function(e,t,n){for(var r,i,o=e.doc,a=n?-1:t-(e.doc.mode.innerMode?1e3:100),l=t;l>a;--l){if(l<=o.first)return o.first;var s=Ke(o,l-1),c=s.stateAfter;if(c&&(!n||l+(c instanceof ct?c.lookAhead:0)<=o.modeFrontier))return l;var u=W(s.text,null,e.options.tabSize);(null==i||r>u)&&(i=l-1,r=u)}return i}(e,t,n),a=o>r.first&&Ke(r,o-1).stateAfter,l=a?ut.fromSaved(r,a,o):new ut(r,Ue(r.mode),o);return r.iter(o,t,(function(n){pt(e,n.text,l);var r=l.line;n.stateAfter=r==t-1||r%5==0||r>=i.viewFrom&&r<i.viewTo?l.save():null,l.nextLine()})),n&&(r.modeFrontier=l.line),l}function pt(e,t,n,r){var i=e.doc.mode,o=new Ve(t,e.options.tabSize,n);for(o.start=o.pos=r||0,""==t&&mt(i,n.state);!o.eol();)gt(i,o,n.state),o.start=o.pos}function mt(e,t){if(e.blankLine)return e.blankLine(t);if(e.innerMode){var n=qe(e,t);return n.mode.blankLine?n.mode.blankLine(n.state):void 0}}function gt(e,t,n,r){for(var i=0;i<10;i++){r&&(r[0]=qe(e,n).mode);var o=e.token(t,n);if(t.pos>t.start)return o}throw new Error("Mode "+e.name+" failed to advance stream.")}ut.prototype.lookAhead=function(e){var t=this.doc.getLine(this.line+e);return null!=t&&e>this.maxLookAhead&&(this.maxLookAhead=e),t},ut.prototype.baseToken=function(e){if(!this.baseTokens)return null;for(;this.baseTokens[this.baseTokenPos]<=e;)this.baseTokenPos+=2;var t=this.baseTokens[this.baseTokenPos+1];return{type:t&&t.replace(/( |^)overlay .*/,""),size:this.baseTokens[this.baseTokenPos]-e}},ut.prototype.nextLine=function(){this.line++,this.maxLookAhead>0&&this.maxLookAhead--},ut.fromSaved=function(e,t,n){return t instanceof ct?new ut(e,je(e.mode,t.state),n,t.lookAhead):new ut(e,je(e.mode,t),n)},ut.prototype.save=function(e){var t=!1!==e?je(this.doc.mode,this.state):this.state;return this.maxLookAhead>0?new ct(t,this.maxLookAhead):t};var vt=function(e,t,n){this.start=e.start,this.end=e.pos,this.string=e.current(),this.type=t||null,this.state=n};function yt(e,t,n,r){var i,o,a=e.doc,l=a.mode,s=Ke(a,(t=lt(a,t)).line),c=ht(e,t.line,n),u=new Ve(s.text,e.options.tabSize,c);for(r&&(o=[]);(r||u.pos<t.ch)&&!u.eol();)u.start=u.pos,i=gt(l,u,c.state),r&&o.push(new vt(u,i,je(a.mode,c.state)));return r?o:new vt(u,i,c.state)}function bt(e,t){if(e)for(;;){var n=e.match(/(?:^|\s+)line-(background-)?(\S+)/);if(!n)break;e=e.slice(0,n.index)+e.slice(n.index+n[0].length);var r=n[1]?"bgClass":"textClass";null==t[r]?t[r]=n[2]:new RegExp("(?:^|\\s)"+n[2]+"(?:$|\\s)").test(t[r])||(t[r]+=" "+n[2])}return e}function xt(e,t,n,r,i,o,a){var l=n.flattenSpans;null==l&&(l=e.options.flattenSpans);var s,c=0,u=null,f=new Ve(t,e.options.tabSize,r),d=e.options.addModeClass&&[null];for(""==t&&bt(mt(n,r.state),o);!f.eol();){if(f.pos>e.options.maxHighlightLength?(l=!1,a&&pt(e,t,r,f.pos),f.pos=t.length,s=null):s=bt(gt(n,f,r.state,d),o),d){var h=d[0].name;h&&(s="m-"+(s?h+" "+s:h))}if(!l||u!=s){for(;c<f.start;)i(c=Math.min(f.start,c+5e3),u);u=s}f.start=f.pos}for(;c<f.pos;){var p=Math.min(f.pos,c+5e3);i(p,u),c=p}}var wt=!1,kt=!1;function Ct(e,t,n){this.marker=e,this.from=t,this.to=n}function St(e,t){if(e)for(var n=0;n<e.length;++n){var r=e[n];if(r.marker==t)return r}}function Tt(e,t){for(var n,r=0;r<e.length;++r)e[r]!=t&&(n||(n=[])).push(e[r]);return n}function Lt(e,t){if(t.full)return null;var n=Qe(e,t.from.line)&&Ke(e,t.from.line).markedSpans,r=Qe(e,t.to.line)&&Ke(e,t.to.line).markedSpans;if(!n&&!r)return null;var i=t.from.ch,o=t.to.ch,a=0==tt(t.from,t.to),l=function(e,t,n){var r;if(e)for(var i=0;i<e.length;++i){var o=e[i],a=o.marker;if(null==o.from||(a.inclusiveLeft?o.from<=t:o.from<t)||o.from==t&&"bookmark"==a.type&&(!n||!o.marker.insertLeft)){var l=null==o.to||(a.inclusiveRight?o.to>=t:o.to>t);(r||(r=[])).push(new Ct(a,o.from,l?null:o.to))}}return r}(n,i,a),s=function(e,t,n){var r;if(e)for(var i=0;i<e.length;++i){var o=e[i],a=o.marker;if(null==o.to||(a.inclusiveRight?o.to>=t:o.to>t)||o.from==t&&"bookmark"==a.type&&(!n||o.marker.insertLeft)){var l=null==o.from||(a.inclusiveLeft?o.from<=t:o.from<t);(r||(r=[])).push(new Ct(a,l?null:o.from-t,null==o.to?null:o.to-t))}}return r}(r,o,a),c=1==t.text.length,u=G(t.text).length+(c?i:0);if(l)for(var f=0;f<l.length;++f){var d=l[f];if(null==d.to){var h=St(s,d.marker);h?c&&(d.to=null==h.to?null:h.to+u):d.to=i}}if(s)for(var p=0;p<s.length;++p){var m=s[p];null!=m.to&&(m.to+=u),null==m.from?St(l,m.marker)||(m.from=u,c&&(l||(l=[])).push(m)):(m.from+=u,c&&(l||(l=[])).push(m))}l&&(l=Mt(l)),s&&s!=l&&(s=Mt(s));var g=[l];if(!c){var v,y=t.text.length-2;if(y>0&&l)for(var b=0;b<l.length;++b)null==l[b].to&&(v||(v=[])).push(new Ct(l[b].marker,null,null));for(var x=0;x<y;++x)g.push(v);g.push(s)}return g}function Mt(e){for(var t=0;t<e.length;++t){var n=e[t];null!=n.from&&n.from==n.to&&!1!==n.marker.clearWhenEmpty&&e.splice(t--,1)}return e.length?e:null}function Ot(e){var t=e.markedSpans;if(t){for(var n=0;n<t.length;++n)t[n].marker.detachLine(e);e.markedSpans=null}}function Nt(e,t){if(t){for(var n=0;n<t.length;++n)t[n].marker.attachLine(e);e.markedSpans=t}}function At(e){return e.inclusiveLeft?-1:0}function Et(e){return e.inclusiveRight?1:0}function zt(e,t){var n=e.lines.length-t.lines.length;if(0!=n)return n;var r=e.find(),i=t.find(),o=tt(r.from,i.from)||At(e)-At(t);if(o)return-o;var a=tt(r.to,i.to)||Et(e)-Et(t);return a||t.id-e.id}function Pt(e,t){var n,r=kt&&e.markedSpans;if(r)for(var i=void 0,o=0;o<r.length;++o)(i=r[o]).marker.collapsed&&null==(t?i.from:i.to)&&(!n||zt(n,i.marker)<0)&&(n=i.marker);return n}function Dt(e){return Pt(e,!0)}function It(e){return Pt(e,!1)}function Ft(e,t){var n,r=kt&&e.markedSpans;if(r)for(var i=0;i<r.length;++i){var o=r[i];o.marker.collapsed&&(null==o.from||o.from<t)&&(null==o.to||o.to>t)&&(!n||zt(n,o.marker)<0)&&(n=o.marker)}return n}function _t(e,t,n,r,i){var o=Ke(e,t),a=kt&&o.markedSpans;if(a)for(var l=0;l<a.length;++l){var s=a[l];if(s.marker.collapsed){var c=s.marker.find(0),u=tt(c.from,n)||At(s.marker)-At(i),f=tt(c.to,r)||Et(s.marker)-Et(i);if(!(u>=0&&f<=0||u<=0&&f>=0)&&(u<=0&&(s.marker.inclusiveRight&&i.inclusiveLeft?tt(c.to,n)>=0:tt(c.to,n)>0)||u>=0&&(s.marker.inclusiveRight&&i.inclusiveLeft?tt(c.from,r)<=0:tt(c.from,r)<0)))return!0}}}function Wt(e){for(var t;t=Dt(e);)e=t.find(-1,!0).line;return e}function Ht(e,t){var n=Ke(e,t),r=Wt(n);return n==r?t:Ze(r)}function Rt(e,t){if(t>e.lastLine())return t;var n,r=Ke(e,t);if(!Bt(e,r))return t;for(;n=It(r);)r=n.find(1,!0).line;return Ze(r)+1}function Bt(e,t){var n=kt&&t.markedSpans;if(n)for(var r=void 0,i=0;i<n.length;++i)if((r=n[i]).marker.collapsed){if(null==r.from)return!0;if(!r.marker.widgetNode&&0==r.from&&r.marker.inclusiveLeft&&jt(e,t,r))return!0}}function jt(e,t,n){if(null==n.to){var r=n.marker.find(1,!0);return jt(e,r.line,St(r.line.markedSpans,n.marker))}if(n.marker.inclusiveRight&&n.to==t.text.length)return!0;for(var i=void 0,o=0;o<t.markedSpans.length;++o)if((i=t.markedSpans[o]).marker.collapsed&&!i.marker.widgetNode&&i.from==n.to&&(null==i.to||i.to!=n.from)&&(i.marker.inclusiveLeft||n.marker.inclusiveRight)&&jt(e,t,i))return!0}function qt(e){for(var t=0,n=(e=Wt(e)).parent,r=0;r<n.lines.length;++r){var i=n.lines[r];if(i==e)break;t+=i.height}for(var o=n.parent;o;o=(n=o).parent)for(var a=0;a<o.children.length;++a){var l=o.children[a];if(l==n)break;t+=l.height}return t}function Ut(e){if(0==e.height)return 0;for(var t,n=e.text.length,r=e;t=Dt(r);){var i=t.find(0,!0);r=i.from.line,n+=i.from.ch-i.to.ch}for(r=e;t=It(r);){var o=t.find(0,!0);n-=r.text.length-o.from.ch,n+=(r=o.to.line).text.length-o.to.ch}return n}function Vt(e){var t=e.display,n=e.doc;t.maxLine=Ke(n,n.first),t.maxLineLength=Ut(t.maxLine),t.maxLineChanged=!0,n.iter((function(e){var n=Ut(e);n>t.maxLineLength&&(t.maxLineLength=n,t.maxLine=e)}))}var Kt=function(e,t,n){this.text=e,Nt(this,t),this.height=n?n(this):1};function $t(e){e.parent=null,Ot(e)}Kt.prototype.lineNo=function(){return Ze(this)},ye(Kt);var Gt={},Xt={};function Zt(e,t){if(!e||/^\s*$/.test(e))return null;var n=t.addModeClass?Xt:Gt;return n[e]||(n[e]=e.replace(/\S+/g,"cm-$&"))}function Yt(e,t){var n=A("span",null,null,s?"padding-right: .1px":null),r={pre:A("pre",[n],"CodeMirror-line"),content:n,col:0,pos:0,cm:e,trailingSpace:!1,splitSpaces:e.getOption("lineWrapping")};t.measure={};for(var i=0;i<=(t.rest?t.rest.length:0);i++){var o=i?t.rest[i-1]:t.line,a=void 0;r.pos=0,r.addToken=Jt,Ne(e.display.measure)&&(a=ce(o,e.doc.direction))&&(r.addToken=en(r.addToken,a)),r.map=[],nn(o,r,dt(e,o,t!=e.display.externalMeasured&&Ze(o))),o.styleClasses&&(o.styleClasses.bgClass&&(r.bgClass=D(o.styleClasses.bgClass,r.bgClass||"")),o.styleClasses.textClass&&(r.textClass=D(o.styleClasses.textClass,r.textClass||""))),0==r.map.length&&r.map.push(0,0,r.content.appendChild(Oe(e.display.measure))),0==i?(t.measure.map=r.map,t.measure.cache={}):((t.measure.maps||(t.measure.maps=[])).push(r.map),(t.measure.caches||(t.measure.caches=[])).push({}))}if(s){var l=r.content.lastChild;(/\bcm-tab\b/.test(l.className)||l.querySelector&&l.querySelector(".cm-tab"))&&(r.content.className="cm-tab-wrap-hack")}return pe(e,"renderLine",e,t.line,r.pre),r.pre.className&&(r.textClass=D(r.pre.className,r.textClass||"")),r}function Qt(e){var t=N("span","•","cm-invalidchar");return t.title="\\u"+e.charCodeAt(0).toString(16),t.setAttribute("aria-label",t.title),t}function Jt(e,t,n,r,i,o,s){if(t){var c,u=e.splitSpaces?function(e,t){if(e.length>1&&!/ /.test(e))return e;for(var n=t,r="",i=0;i<e.length;i++){var o=e.charAt(i);" "!=o||!n||i!=e.length-1&&32!=e.charCodeAt(i+1)||(o=" "),r+=o,n=" "==o}return r}(t,e.trailingSpace):t,f=e.cm.state.specialChars,d=!1;if(f.test(t)){c=document.createDocumentFragment();for(var h=0;;){f.lastIndex=h;var p=f.exec(t),m=p?p.index-h:t.length-h;if(m){var g=document.createTextNode(u.slice(h,h+m));a&&l<9?c.appendChild(N("span",[g])):c.appendChild(g),e.map.push(e.pos,e.pos+m,g),e.col+=m,e.pos+=m}if(!p)break;h+=m+1;var v=void 0;if("\t"==p[0]){var y=e.cm.options.tabSize,b=y-e.col%y;(v=c.appendChild(N("span",$(b),"cm-tab"))).setAttribute("role","presentation"),v.setAttribute("cm-text","\t"),e.col+=b}else"\r"==p[0]||"\n"==p[0]?((v=c.appendChild(N("span","\r"==p[0]?"␍":"␤","cm-invalidchar"))).setAttribute("cm-text",p[0]),e.col+=1):((v=e.cm.options.specialCharPlaceholder(p[0])).setAttribute("cm-text",p[0]),a&&l<9?c.appendChild(N("span",[v])):c.appendChild(v),e.col+=1);e.map.push(e.pos,e.pos+1,v),e.pos++}}else e.col+=t.length,c=document.createTextNode(u),e.map.push(e.pos,e.pos+t.length,c),a&&l<9&&(d=!0),e.pos+=t.length;if(e.trailingSpace=32==u.charCodeAt(t.length-1),n||r||i||d||o||s){var x=n||"";r&&(x+=r),i&&(x+=i);var w=N("span",[c],x,o);if(s)for(var k in s)s.hasOwnProperty(k)&&"style"!=k&&"class"!=k&&w.setAttribute(k,s[k]);return e.content.appendChild(w)}e.content.appendChild(c)}}function en(e,t){return function(n,r,i,o,a,l,s){i=i?i+" cm-force-border":"cm-force-border";for(var c=n.pos,u=c+r.length;;){for(var f=void 0,d=0;d<t.length&&!((f=t[d]).to>c&&f.from<=c);d++);if(f.to>=u)return e(n,r,i,o,a,l,s);e(n,r.slice(0,f.to-c),i,o,null,l,s),o=null,r=r.slice(f.to-c),c=f.to}}}function tn(e,t,n,r){var i=!r&&n.widgetNode;i&&e.map.push(e.pos,e.pos+t,i),!r&&e.cm.display.input.needsContentAttribute&&(i||(i=e.content.appendChild(document.createElement("span"))),i.setAttribute("cm-marker",n.id)),i&&(e.cm.display.input.setUneditable(i),e.content.appendChild(i)),e.pos+=t,e.trailingSpace=!1}function nn(e,t,n){var r=e.markedSpans,i=e.text,o=0;if(r)for(var a,l,s,c,u,f,d,h=i.length,p=0,m=1,g="",v=0;;){if(v==p){s=c=u=l="",d=null,f=null,v=1/0;for(var y=[],b=void 0,x=0;x<r.length;++x){var w=r[x],k=w.marker;if("bookmark"==k.type&&w.from==p&&k.widgetNode)y.push(k);else if(w.from<=p&&(null==w.to||w.to>p||k.collapsed&&w.to==p&&w.from==p)){if(null!=w.to&&w.to!=p&&v>w.to&&(v=w.to,c=""),k.className&&(s+=" "+k.className),k.css&&(l=(l?l+";":"")+k.css),k.startStyle&&w.from==p&&(u+=" "+k.startStyle),k.endStyle&&w.to==v&&(b||(b=[])).push(k.endStyle,w.to),k.title&&((d||(d={})).title=k.title),k.attributes)for(var C in k.attributes)(d||(d={}))[C]=k.attributes[C];k.collapsed&&(!f||zt(f.marker,k)<0)&&(f=w)}else w.from>p&&v>w.from&&(v=w.from)}if(b)for(var S=0;S<b.length;S+=2)b[S+1]==v&&(c+=" "+b[S]);if(!f||f.from==p)for(var T=0;T<y.length;++T)tn(t,0,y[T]);if(f&&(f.from||0)==p){if(tn(t,(null==f.to?h+1:f.to)-p,f.marker,null==f.from),null==f.to)return;f.to==p&&(f=!1)}}if(p>=h)break;for(var L=Math.min(h,v);;){if(g){var M=p+g.length;if(!f){var O=M>L?g.slice(0,L-p):g;t.addToken(t,O,a?a+s:s,u,p+O.length==v?c:"",l,d)}if(M>=L){g=g.slice(L-p),p=L;break}p=M,u=""}g=i.slice(o,o=n[m++]),a=Zt(n[m++],t.cm.options)}}else for(var N=1;N<n.length;N+=2)t.addToken(t,i.slice(o,o=n[N]),Zt(n[N+1],t.cm.options))}function rn(e,t,n){this.line=t,this.rest=function(e){for(var t,n;t=It(e);)e=t.find(1,!0).line,(n||(n=[])).push(e);return n}(t),this.size=this.rest?Ze(G(this.rest))-n+1:1,this.node=this.text=null,this.hidden=Bt(e,t)}function on(e,t,n){for(var r,i=[],o=t;o<n;o=r){var a=new rn(e.doc,Ke(e.doc,o),o);r=o+a.size,i.push(a)}return i}var an=null,ln=null;function sn(e,t){var n=de(e,t);if(n.length){var r,i=Array.prototype.slice.call(arguments,2);an?r=an.delayedCallbacks:ln?r=ln:(r=ln=[],setTimeout(cn,0));for(var o=function(e){r.push((function(){return n[e].apply(null,i)}))},a=0;a<n.length;++a)o(a)}}function cn(){var e=ln;ln=null;for(var t=0;t<e.length;++t)e[t]()}function un(e,t,n,r){for(var i=0;i<t.changes.length;i++){var o=t.changes[i];"text"==o?hn(e,t):"gutter"==o?mn(e,t,n,r):"class"==o?pn(e,t):"widget"==o&&gn(e,t,r)}t.changes=null}function fn(e){return e.node==e.text&&(e.node=N("div",null,null,"position: relative"),e.text.parentNode&&e.text.parentNode.replaceChild(e.node,e.text),e.node.appendChild(e.text),a&&l<8&&(e.node.style.zIndex=2)),e.node}function dn(e,t){var n=e.display.externalMeasured;return n&&n.line==t.line?(e.display.externalMeasured=null,t.measure=n.measure,n.built):Yt(e,t)}function hn(e,t){var n=t.text.className,r=dn(e,t);t.text==t.node&&(t.node=r.pre),t.text.parentNode.replaceChild(r.pre,t.text),t.text=r.pre,r.bgClass!=t.bgClass||r.textClass!=t.textClass?(t.bgClass=r.bgClass,t.textClass=r.textClass,pn(e,t)):n&&(t.text.className=n)}function pn(e,t){!function(e,t){var n=t.bgClass?t.bgClass+" "+(t.line.bgClass||""):t.line.bgClass;if(n&&(n+=" CodeMirror-linebackground"),t.background)n?t.background.className=n:(t.background.parentNode.removeChild(t.background),t.background=null);else if(n){var r=fn(t);t.background=r.insertBefore(N("div",null,n),r.firstChild),e.display.input.setUneditable(t.background)}}(e,t),t.line.wrapClass?fn(t).className=t.line.wrapClass:t.node!=t.text&&(t.node.className="");var n=t.textClass?t.textClass+" "+(t.line.textClass||""):t.line.textClass;t.text.className=n||""}function mn(e,t,n,r){if(t.gutter&&(t.node.removeChild(t.gutter),t.gutter=null),t.gutterBackground&&(t.node.removeChild(t.gutterBackground),t.gutterBackground=null),t.line.gutterClass){var i=fn(t);t.gutterBackground=N("div",null,"CodeMirror-gutter-background "+t.line.gutterClass,"left: "+(e.options.fixedGutter?r.fixedPos:-r.gutterTotalWidth)+"px; width: "+r.gutterTotalWidth+"px"),e.display.input.setUneditable(t.gutterBackground),i.insertBefore(t.gutterBackground,t.text)}var o=t.line.gutterMarkers;if(e.options.lineNumbers||o){var a=fn(t),l=t.gutter=N("div",null,"CodeMirror-gutter-wrapper","left: "+(e.options.fixedGutter?r.fixedPos:-r.gutterTotalWidth)+"px");if(e.display.input.setUneditable(l),a.insertBefore(l,t.text),t.line.gutterClass&&(l.className+=" "+t.line.gutterClass),!e.options.lineNumbers||o&&o["CodeMirror-linenumbers"]||(t.lineNumber=l.appendChild(N("div",Je(e.options,n),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+r.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+e.display.lineNumInnerWidth+"px"))),o)for(var s=0;s<e.display.gutterSpecs.length;++s){var c=e.display.gutterSpecs[s].className,u=o.hasOwnProperty(c)&&o[c];u&&l.appendChild(N("div",[u],"CodeMirror-gutter-elt","left: "+r.gutterLeft[c]+"px; width: "+r.gutterWidth[c]+"px"))}}}function gn(e,t,n){t.alignable&&(t.alignable=null);for(var r=S("CodeMirror-linewidget"),i=t.node.firstChild,o=void 0;i;i=o)o=i.nextSibling,r.test(i.className)&&t.node.removeChild(i);yn(e,t,n)}function vn(e,t,n,r){var i=dn(e,t);return t.text=t.node=i.pre,i.bgClass&&(t.bgClass=i.bgClass),i.textClass&&(t.textClass=i.textClass),pn(e,t),mn(e,t,n,r),yn(e,t,r),t.node}function yn(e,t,n){if(bn(e,t.line,t,n,!0),t.rest)for(var r=0;r<t.rest.length;r++)bn(e,t.rest[r],t,n,!1)}function bn(e,t,n,r,i){if(t.widgets)for(var o=fn(n),a=0,l=t.widgets;a<l.length;++a){var s=l[a],c=N("div",[s.node],"CodeMirror-linewidget"+(s.className?" "+s.className:""));s.handleMouseEvents||c.setAttribute("cm-ignore-events","true"),xn(s,c,n,r),e.display.input.setUneditable(c),i&&s.above?o.insertBefore(c,n.gutter||n.text):o.appendChild(c),sn(s,"redraw")}}function xn(e,t,n,r){if(e.noHScroll){(n.alignable||(n.alignable=[])).push(t);var i=r.wrapperWidth;t.style.left=r.fixedPos+"px",e.coverGutter||(i-=r.gutterTotalWidth,t.style.paddingLeft=r.gutterTotalWidth+"px"),t.style.width=i+"px"}e.coverGutter&&(t.style.zIndex=5,t.style.position="relative",e.noHScroll||(t.style.marginLeft=-r.gutterTotalWidth+"px"))}function wn(e){if(null!=e.height)return e.height;var t=e.doc.cm;if(!t)return 0;if(!E(document.body,e.node)){var n="position: relative;";e.coverGutter&&(n+="margin-left: -"+t.display.gutters.offsetWidth+"px;"),e.noHScroll&&(n+="width: "+t.display.wrapper.clientWidth+"px;"),O(t.display.measure,N("div",[e.node],null,n))}return e.height=e.node.parentNode.offsetHeight}function kn(e,t){for(var n=Ce(t);n!=e.wrapper;n=n.parentNode)if(!n||1==n.nodeType&&"true"==n.getAttribute("cm-ignore-events")||n.parentNode==e.sizer&&n!=e.mover)return!0}function Cn(e){return e.lineSpace.offsetTop}function Sn(e){return e.mover.offsetHeight-e.lineSpace.offsetHeight}function Tn(e){if(e.cachedPaddingH)return e.cachedPaddingH;var t=O(e.measure,N("pre","x","CodeMirror-line-like")),n=window.getComputedStyle?window.getComputedStyle(t):t.currentStyle,r={left:parseInt(n.paddingLeft),right:parseInt(n.paddingRight)};return isNaN(r.left)||isNaN(r.right)||(e.cachedPaddingH=r),r}function Ln(e){return 50-e.display.nativeBarWidth}function Mn(e){return e.display.scroller.clientWidth-Ln(e)-e.display.barWidth}function On(e){return e.display.scroller.clientHeight-Ln(e)-e.display.barHeight}function Nn(e,t,n){if(e.line==t)return{map:e.measure.map,cache:e.measure.cache};for(var r=0;r<e.rest.length;r++)if(e.rest[r]==t)return{map:e.measure.maps[r],cache:e.measure.caches[r]};for(var i=0;i<e.rest.length;i++)if(Ze(e.rest[i])>n)return{map:e.measure.maps[i],cache:e.measure.caches[i],before:!0}}function An(e,t,n,r){return Pn(e,zn(e,t),n,r)}function En(e,t){if(t>=e.display.viewFrom&&t<e.display.viewTo)return e.display.view[ur(e,t)];var n=e.display.externalMeasured;return n&&t>=n.lineN&&t<n.lineN+n.size?n:void 0}function zn(e,t){var n=Ze(t),r=En(e,n);r&&!r.text?r=null:r&&r.changes&&(un(e,r,n,or(e)),e.curOp.forceUpdate=!0),r||(r=function(e,t){var n=Ze(t=Wt(t)),r=e.display.externalMeasured=new rn(e.doc,t,n);r.lineN=n;var i=r.built=Yt(e,r);return r.text=i.pre,O(e.display.lineMeasure,i.pre),r}(e,t));var i=Nn(r,t,n);return{line:t,view:r,rect:null,map:i.map,cache:i.cache,before:i.before,hasHeights:!1}}function Pn(e,t,n,r,i){t.before&&(n=-1);var o,s=n+(r||"");return t.cache.hasOwnProperty(s)?o=t.cache[s]:(t.rect||(t.rect=t.view.text.getBoundingClientRect()),t.hasHeights||(function(e,t,n){var r=e.options.lineWrapping,i=r&&Mn(e);if(!t.measure.heights||r&&t.measure.width!=i){var o=t.measure.heights=[];if(r){t.measure.width=i;for(var a=t.text.firstChild.getClientRects(),l=0;l<a.length-1;l++){var s=a[l],c=a[l+1];Math.abs(s.bottom-c.bottom)>2&&o.push((s.bottom+c.top)/2-n.top)}}o.push(n.bottom-n.top)}}(e,t.view,t.rect),t.hasHeights=!0),(o=function(e,t,n,r){var i,o=Fn(t.map,n,r),s=o.node,c=o.start,u=o.end,f=o.collapse;if(3==s.nodeType){for(var d=0;d<4;d++){for(;c&&re(t.line.text.charAt(o.coverStart+c));)--c;for(;o.coverStart+u<o.coverEnd&&re(t.line.text.charAt(o.coverStart+u));)++u;if((i=a&&l<9&&0==c&&u==o.coverEnd-o.coverStart?s.parentNode.getBoundingClientRect():_n(T(s,c,u).getClientRects(),r)).left||i.right||0==c)break;u=c,c-=1,f="right"}a&&l<11&&(i=function(e,t){if(!window.screen||null==screen.logicalXDPI||screen.logicalXDPI==screen.deviceXDPI||!function(e){if(null!=De)return De;var t=O(e,N("span","x")),n=t.getBoundingClientRect(),r=T(t,0,1).getBoundingClientRect();return De=Math.abs(n.left-r.left)>1}(e))return t;var n=screen.logicalXDPI/screen.deviceXDPI,r=screen.logicalYDPI/screen.deviceYDPI;return{left:t.left*n,right:t.right*n,top:t.top*r,bottom:t.bottom*r}}(e.display.measure,i))}else{var h;c>0&&(f=r="right"),i=e.options.lineWrapping&&(h=s.getClientRects()).length>1?h["right"==r?h.length-1:0]:s.getBoundingClientRect()}if(a&&l<9&&!c&&(!i||!i.left&&!i.right)){var p=s.parentNode.getClientRects()[0];i=p?{left:p.left,right:p.left+ir(e.display),top:p.top,bottom:p.bottom}:In}for(var m=i.top-t.rect.top,g=i.bottom-t.rect.top,v=(m+g)/2,y=t.view.measure.heights,b=0;b<y.length-1&&!(v<y[b]);b++);var x=b?y[b-1]:0,w=y[b],k={left:("right"==f?i.right:i.left)-t.rect.left,right:("left"==f?i.left:i.right)-t.rect.left,top:x,bottom:w};return i.left||i.right||(k.bogus=!0),e.options.singleCursorHeightPerLine||(k.rtop=m,k.rbottom=g),k}(e,t,n,r)).bogus||(t.cache[s]=o)),{left:o.left,right:o.right,top:i?o.rtop:o.top,bottom:i?o.rbottom:o.bottom}}var Dn,In={left:0,right:0,top:0,bottom:0};function Fn(e,t,n){for(var r,i,o,a,l,s,c=0;c<e.length;c+=3)if(l=e[c],s=e[c+1],t<l?(i=0,o=1,a="left"):t<s?o=1+(i=t-l):(c==e.length-3||t==s&&e[c+3]>t)&&(i=(o=s-l)-1,t>=s&&(a="right")),null!=i){if(r=e[c+2],l==s&&n==(r.insertLeft?"left":"right")&&(a=n),"left"==n&&0==i)for(;c&&e[c-2]==e[c-3]&&e[c-1].insertLeft;)r=e[2+(c-=3)],a="left";if("right"==n&&i==s-l)for(;c<e.length-3&&e[c+3]==e[c+4]&&!e[c+5].insertLeft;)r=e[(c+=3)+2],a="right";break}return{node:r,start:i,end:o,collapse:a,coverStart:l,coverEnd:s}}function _n(e,t){var n=In;if("left"==t)for(var r=0;r<e.length&&(n=e[r]).left==n.right;r++);else for(var i=e.length-1;i>=0&&(n=e[i]).left==n.right;i--);return n}function Wn(e){if(e.measure&&(e.measure.cache={},e.measure.heights=null,e.rest))for(var t=0;t<e.rest.length;t++)e.measure.caches[t]={}}function Hn(e){e.display.externalMeasure=null,M(e.display.lineMeasure);for(var t=0;t<e.display.view.length;t++)Wn(e.display.view[t])}function Rn(e){Hn(e),e.display.cachedCharWidth=e.display.cachedTextHeight=e.display.cachedPaddingH=null,e.options.lineWrapping||(e.display.maxLineChanged=!0),e.display.lineNumChars=null}function Bn(){return u&&g?-(document.body.getBoundingClientRect().left-parseInt(getComputedStyle(document.body).marginLeft)):window.pageXOffset||(document.documentElement||document.body).scrollLeft}function jn(){return u&&g?-(document.body.getBoundingClientRect().top-parseInt(getComputedStyle(document.body).marginTop)):window.pageYOffset||(document.documentElement||document.body).scrollTop}function qn(e){var t=0;if(e.widgets)for(var n=0;n<e.widgets.length;++n)e.widgets[n].above&&(t+=wn(e.widgets[n]));return t}function Un(e,t,n,r,i){if(!i){var o=qn(t);n.top+=o,n.bottom+=o}if("line"==r)return n;r||(r="local");var a=qt(t);if("local"==r?a+=Cn(e.display):a-=e.display.viewOffset,"page"==r||"window"==r){var l=e.display.lineSpace.getBoundingClientRect();a+=l.top+("window"==r?0:jn());var s=l.left+("window"==r?0:Bn());n.left+=s,n.right+=s}return n.top+=a,n.bottom+=a,n}function Vn(e,t,n){if("div"==n)return t;var r=t.left,i=t.top;if("page"==n)r-=Bn(),i-=jn();else if("local"==n||!n){var o=e.display.sizer.getBoundingClientRect();r+=o.left,i+=o.top}var a=e.display.lineSpace.getBoundingClientRect();return{left:r-a.left,top:i-a.top}}function Kn(e,t,n,r,i){return r||(r=Ke(e.doc,t.line)),Un(e,r,An(e,r,t.ch,i),n)}function $n(e,t,n,r,i,o){function a(t,a){var l=Pn(e,i,t,a?"right":"left",o);return a?l.left=l.right:l.right=l.left,Un(e,r,l,n)}r=r||Ke(e.doc,t.line),i||(i=zn(e,r));var l=ce(r,e.doc.direction),s=t.ch,c=t.sticky;if(s>=r.text.length?(s=r.text.length,c="before"):s<=0&&(s=0,c="after"),!l)return a("before"==c?s-1:s,"before"==c);function u(e,t,n){return a(n?e-1:e,1==l[t].level!=n)}var f=le(l,s,c),d=ae,h=u(s,f,"before"==c);return null!=d&&(h.other=u(s,d,"before"!=c)),h}function Gn(e,t){var n=0;t=lt(e.doc,t),e.options.lineWrapping||(n=ir(e.display)*t.ch);var r=Ke(e.doc,t.line),i=qt(r)+Cn(e.display);return{left:n,right:n,top:i,bottom:i+r.height}}function Xn(e,t,n,r,i){var o=et(e,t,n);return o.xRel=i,r&&(o.outside=r),o}function Zn(e,t,n){var r=e.doc;if((n+=e.display.viewOffset)<0)return Xn(r.first,0,null,-1,-1);var i=Ye(r,n),o=r.first+r.size-1;if(i>o)return Xn(r.first+r.size-1,Ke(r,o).text.length,null,1,1);t<0&&(t=0);for(var a=Ke(r,i);;){var l=er(e,a,i,t,n),s=Ft(a,l.ch+(l.xRel>0||l.outside>0?1:0));if(!s)return l;var c=s.find(1);if(c.line==i)return c;a=Ke(r,i=c.line)}}function Yn(e,t,n,r){r-=qn(t);var i=t.text.length,o=oe((function(t){return Pn(e,n,t-1).bottom<=r}),i,0);return{begin:o,end:i=oe((function(t){return Pn(e,n,t).top>r}),o,i)}}function Qn(e,t,n,r){return n||(n=zn(e,t)),Yn(e,t,n,Un(e,t,Pn(e,n,r),"line").top)}function Jn(e,t,n,r){return!(e.bottom<=n)&&(e.top>n||(r?e.left:e.right)>t)}function er(e,t,n,r,i){i-=qt(t);var o=zn(e,t),a=qn(t),l=0,s=t.text.length,c=!0,u=ce(t,e.doc.direction);if(u){var f=(e.options.lineWrapping?nr:tr)(e,t,n,o,u,r,i);l=(c=1!=f.level)?f.from:f.to-1,s=c?f.to:f.from-1}var d,h,p=null,m=null,g=oe((function(t){var n=Pn(e,o,t);return n.top+=a,n.bottom+=a,!!Jn(n,r,i,!1)&&(n.top<=i&&n.left<=r&&(p=t,m=n),!0)}),l,s),v=!1;if(m){var y=r-m.left<m.right-r,b=y==c;g=p+(b?0:1),h=b?"after":"before",d=y?m.left:m.right}else{c||g!=s&&g!=l||g++,h=0==g?"after":g==t.text.length?"before":Pn(e,o,g-(c?1:0)).bottom+a<=i==c?"after":"before";var x=$n(e,et(n,g,h),"line",t,o);d=x.left,v=i<x.top?-1:i>=x.bottom?1:0}return Xn(n,g=ie(t.text,g,1),h,v,r-d)}function tr(e,t,n,r,i,o,a){var l=oe((function(l){var s=i[l],c=1!=s.level;return Jn($n(e,et(n,c?s.to:s.from,c?"before":"after"),"line",t,r),o,a,!0)}),0,i.length-1),s=i[l];if(l>0){var c=1!=s.level,u=$n(e,et(n,c?s.from:s.to,c?"after":"before"),"line",t,r);Jn(u,o,a,!0)&&u.top>a&&(s=i[l-1])}return s}function nr(e,t,n,r,i,o,a){var l=Yn(e,t,r,a),s=l.begin,c=l.end;/\s/.test(t.text.charAt(c-1))&&c--;for(var u=null,f=null,d=0;d<i.length;d++){var h=i[d];if(!(h.from>=c||h.to<=s)){var p=Pn(e,r,1!=h.level?Math.min(c,h.to)-1:Math.max(s,h.from)).right,m=p<o?o-p+1e9:p-o;(!u||f>m)&&(u=h,f=m)}}return u||(u=i[i.length-1]),u.from<s&&(u={from:s,to:u.to,level:u.level}),u.to>c&&(u={from:u.from,to:c,level:u.level}),u}function rr(e){if(null!=e.cachedTextHeight)return e.cachedTextHeight;if(null==Dn){Dn=N("pre",null,"CodeMirror-line-like");for(var t=0;t<49;++t)Dn.appendChild(document.createTextNode("x")),Dn.appendChild(N("br"));Dn.appendChild(document.createTextNode("x"))}O(e.measure,Dn);var n=Dn.offsetHeight/50;return n>3&&(e.cachedTextHeight=n),M(e.measure),n||1}function ir(e){if(null!=e.cachedCharWidth)return e.cachedCharWidth;var t=N("span","xxxxxxxxxx"),n=N("pre",[t],"CodeMirror-line-like");O(e.measure,n);var r=t.getBoundingClientRect(),i=(r.right-r.left)/10;return i>2&&(e.cachedCharWidth=i),i||10}function or(e){for(var t=e.display,n={},r={},i=t.gutters.clientLeft,o=t.gutters.firstChild,a=0;o;o=o.nextSibling,++a){var l=e.display.gutterSpecs[a].className;n[l]=o.offsetLeft+o.clientLeft+i,r[l]=o.clientWidth}return{fixedPos:ar(t),gutterTotalWidth:t.gutters.offsetWidth,gutterLeft:n,gutterWidth:r,wrapperWidth:t.wrapper.clientWidth}}function ar(e){return e.scroller.getBoundingClientRect().left-e.sizer.getBoundingClientRect().left}function lr(e){var t=rr(e.display),n=e.options.lineWrapping,r=n&&Math.max(5,e.display.scroller.clientWidth/ir(e.display)-3);return function(i){if(Bt(e.doc,i))return 0;var o=0;if(i.widgets)for(var a=0;a<i.widgets.length;a++)i.widgets[a].height&&(o+=i.widgets[a].height);return n?o+(Math.ceil(i.text.length/r)||1)*t:o+t}}function sr(e){var t=e.doc,n=lr(e);t.iter((function(e){var t=n(e);t!=e.height&&Xe(e,t)}))}function cr(e,t,n,r){var i=e.display;if(!n&&"true"==Ce(t).getAttribute("cm-not-content"))return null;var o,a,l=i.lineSpace.getBoundingClientRect();try{o=t.clientX-l.left,a=t.clientY-l.top}catch(e){return null}var s,c=Zn(e,o,a);if(r&&c.xRel>0&&(s=Ke(e.doc,c.line).text).length==c.ch){var u=W(s,s.length,e.options.tabSize)-s.length;c=et(c.line,Math.max(0,Math.round((o-Tn(e.display).left)/ir(e.display))-u))}return c}function ur(e,t){if(t>=e.display.viewTo)return null;if((t-=e.display.viewFrom)<0)return null;for(var n=e.display.view,r=0;r<n.length;r++)if((t-=n[r].size)<0)return r}function fr(e,t,n,r){null==t&&(t=e.doc.first),null==n&&(n=e.doc.first+e.doc.size),r||(r=0);var i=e.display;if(r&&n<i.viewTo&&(null==i.updateLineNumbers||i.updateLineNumbers>t)&&(i.updateLineNumbers=t),e.curOp.viewChanged=!0,t>=i.viewTo)kt&&Ht(e.doc,t)<i.viewTo&&hr(e);else if(n<=i.viewFrom)kt&&Rt(e.doc,n+r)>i.viewFrom?hr(e):(i.viewFrom+=r,i.viewTo+=r);else if(t<=i.viewFrom&&n>=i.viewTo)hr(e);else if(t<=i.viewFrom){var o=pr(e,n,n+r,1);o?(i.view=i.view.slice(o.index),i.viewFrom=o.lineN,i.viewTo+=r):hr(e)}else if(n>=i.viewTo){var a=pr(e,t,t,-1);a?(i.view=i.view.slice(0,a.index),i.viewTo=a.lineN):hr(e)}else{var l=pr(e,t,t,-1),s=pr(e,n,n+r,1);l&&s?(i.view=i.view.slice(0,l.index).concat(on(e,l.lineN,s.lineN)).concat(i.view.slice(s.index)),i.viewTo+=r):hr(e)}var c=i.externalMeasured;c&&(n<c.lineN?c.lineN+=r:t<c.lineN+c.size&&(i.externalMeasured=null))}function dr(e,t,n){e.curOp.viewChanged=!0;var r=e.display,i=e.display.externalMeasured;if(i&&t>=i.lineN&&t<i.lineN+i.size&&(r.externalMeasured=null),!(t<r.viewFrom||t>=r.viewTo)){var o=r.view[ur(e,t)];if(null!=o.node){var a=o.changes||(o.changes=[]);-1==R(a,n)&&a.push(n)}}}function hr(e){e.display.viewFrom=e.display.viewTo=e.doc.first,e.display.view=[],e.display.viewOffset=0}function pr(e,t,n,r){var i,o=ur(e,t),a=e.display.view;if(!kt||n==e.doc.first+e.doc.size)return{index:o,lineN:n};for(var l=e.display.viewFrom,s=0;s<o;s++)l+=a[s].size;if(l!=t){if(r>0){if(o==a.length-1)return null;i=l+a[o].size-t,o++}else i=l-t;t+=i,n+=i}for(;Ht(e.doc,n)!=n;){if(o==(r<0?0:a.length-1))return null;n+=r*a[o-(r<0?1:0)].size,o+=r}return{index:o,lineN:n}}function mr(e){for(var t=e.display.view,n=0,r=0;r<t.length;r++){var i=t[r];i.hidden||i.node&&!i.changes||++n}return n}function gr(e){e.display.input.showSelection(e.display.input.prepareSelection())}function vr(e,t){void 0===t&&(t=!0);for(var n=e.doc,r={},i=r.cursors=document.createDocumentFragment(),o=r.selection=document.createDocumentFragment(),a=0;a<n.sel.ranges.length;a++)if(t||a!=n.sel.primIndex){var l=n.sel.ranges[a];if(!(l.from().line>=e.display.viewTo||l.to().line<e.display.viewFrom)){var s=l.empty();(s||e.options.showCursorWhenSelecting)&&yr(e,l.head,i),s||xr(e,l,o)}}return r}function yr(e,t,n){var r=$n(e,t,"div",null,null,!e.options.singleCursorHeightPerLine),i=n.appendChild(N("div"," ","CodeMirror-cursor"));if(i.style.left=r.left+"px",i.style.top=r.top+"px",i.style.height=Math.max(0,r.bottom-r.top)*e.options.cursorHeight+"px",r.other){var o=n.appendChild(N("div"," ","CodeMirror-cursor CodeMirror-secondarycursor"));o.style.display="",o.style.left=r.other.left+"px",o.style.top=r.other.top+"px",o.style.height=.85*(r.other.bottom-r.other.top)+"px"}}function br(e,t){return e.top-t.top||e.left-t.left}function xr(e,t,n){var r=e.display,i=e.doc,o=document.createDocumentFragment(),a=Tn(e.display),l=a.left,s=Math.max(r.sizerWidth,Mn(e)-r.sizer.offsetLeft)-a.right,c="ltr"==i.direction;function u(e,t,n,r){t<0&&(t=0),t=Math.round(t),r=Math.round(r),o.appendChild(N("div",null,"CodeMirror-selected","position: absolute; left: "+e+"px;\n top: "+t+"px; width: "+(null==n?s-e:n)+"px;\n height: "+(r-t)+"px"))}function f(t,n,r){var o,a,f=Ke(i,t),d=f.text.length;function h(n,r){return Kn(e,et(t,n),"div",f,r)}function p(t,n,r){var i=Qn(e,f,null,t),o="ltr"==n==("after"==r)?"left":"right";return h("after"==r?i.begin:i.end-(/\s/.test(f.text.charAt(i.end-1))?2:1),o)[o]}var m=ce(f,i.direction);return function(e,t,n,r){if(!e)return r(t,n,"ltr",0);for(var i=!1,o=0;o<e.length;++o){var a=e[o];(a.from<n&&a.to>t||t==n&&a.to==t)&&(r(Math.max(a.from,t),Math.min(a.to,n),1==a.level?"rtl":"ltr",o),i=!0)}i||r(t,n,"ltr")}(m,n||0,null==r?d:r,(function(e,t,i,f){var g="ltr"==i,v=h(e,g?"left":"right"),y=h(t-1,g?"right":"left"),b=null==n&&0==e,x=null==r&&t==d,w=0==f,k=!m||f==m.length-1;if(y.top-v.top<=3){var C=(c?x:b)&&k,S=(c?b:x)&&w?l:(g?v:y).left,T=C?s:(g?y:v).right;u(S,v.top,T-S,v.bottom)}else{var L,M,O,N;g?(L=c&&b&&w?l:v.left,M=c?s:p(e,i,"before"),O=c?l:p(t,i,"after"),N=c&&x&&k?s:y.right):(L=c?p(e,i,"before"):l,M=!c&&b&&w?s:v.right,O=!c&&x&&k?l:y.left,N=c?p(t,i,"after"):s),u(L,v.top,M-L,v.bottom),v.bottom<y.top&&u(l,v.bottom,null,y.top),u(O,y.top,N-O,y.bottom)}(!o||br(v,o)<0)&&(o=v),br(y,o)<0&&(o=y),(!a||br(v,a)<0)&&(a=v),br(y,a)<0&&(a=y)})),{start:o,end:a}}var d=t.from(),h=t.to();if(d.line==h.line)f(d.line,d.ch,h.ch);else{var p=Ke(i,d.line),m=Ke(i,h.line),g=Wt(p)==Wt(m),v=f(d.line,d.ch,g?p.text.length+1:null).end,y=f(h.line,g?0:null,h.ch).start;g&&(v.top<y.top-2?(u(v.right,v.top,null,v.bottom),u(l,y.top,y.left,y.bottom)):u(v.right,v.top,y.left-v.right,v.bottom)),v.bottom<y.top&&u(l,v.bottom,null,y.top)}n.appendChild(o)}function wr(e){if(e.state.focused){var t=e.display;clearInterval(t.blinker);var n=!0;t.cursorDiv.style.visibility="",e.options.cursorBlinkRate>0?t.blinker=setInterval((function(){e.hasFocus()||Tr(e),t.cursorDiv.style.visibility=(n=!n)?"":"hidden"}),e.options.cursorBlinkRate):e.options.cursorBlinkRate<0&&(t.cursorDiv.style.visibility="hidden")}}function kr(e){e.state.focused||(e.display.input.focus(),Sr(e))}function Cr(e){e.state.delayingBlurEvent=!0,setTimeout((function(){e.state.delayingBlurEvent&&(e.state.delayingBlurEvent=!1,Tr(e))}),100)}function Sr(e,t){e.state.delayingBlurEvent&&(e.state.delayingBlurEvent=!1),"nocursor"!=e.options.readOnly&&(e.state.focused||(pe(e,"focus",e,t),e.state.focused=!0,P(e.display.wrapper,"CodeMirror-focused"),e.curOp||e.display.selForContextMenu==e.doc.sel||(e.display.input.reset(),s&&setTimeout((function(){return e.display.input.reset(!0)}),20)),e.display.input.receivedFocus()),wr(e))}function Tr(e,t){e.state.delayingBlurEvent||(e.state.focused&&(pe(e,"blur",e,t),e.state.focused=!1,L(e.display.wrapper,"CodeMirror-focused")),clearInterval(e.display.blinker),setTimeout((function(){e.state.focused||(e.display.shift=!1)}),150))}function Lr(e){for(var t=e.display,n=t.lineDiv.offsetTop,r=0;r<t.view.length;r++){var i=t.view[r],o=e.options.lineWrapping,s=void 0,c=0;if(!i.hidden){if(a&&l<8){var u=i.node.offsetTop+i.node.offsetHeight;s=u-n,n=u}else{var f=i.node.getBoundingClientRect();s=f.bottom-f.top,!o&&i.text.firstChild&&(c=i.text.firstChild.getBoundingClientRect().right-f.left-1)}var d=i.line.height-s;if((d>.005||d<-.005)&&(Xe(i.line,s),Mr(i.line),i.rest))for(var h=0;h<i.rest.length;h++)Mr(i.rest[h]);if(c>e.display.sizerWidth){var p=Math.ceil(c/ir(e.display));p>e.display.maxLineLength&&(e.display.maxLineLength=p,e.display.maxLine=i.line,e.display.maxLineChanged=!0)}}}}function Mr(e){if(e.widgets)for(var t=0;t<e.widgets.length;++t){var n=e.widgets[t],r=n.node.parentNode;r&&(n.height=r.offsetHeight)}}function Or(e,t,n){var r=n&&null!=n.top?Math.max(0,n.top):e.scroller.scrollTop;r=Math.floor(r-Cn(e));var i=n&&null!=n.bottom?n.bottom:r+e.wrapper.clientHeight,o=Ye(t,r),a=Ye(t,i);if(n&&n.ensure){var l=n.ensure.from.line,s=n.ensure.to.line;l<o?(o=l,a=Ye(t,qt(Ke(t,l))+e.wrapper.clientHeight)):Math.min(s,t.lastLine())>=a&&(o=Ye(t,qt(Ke(t,s))-e.wrapper.clientHeight),a=s)}return{from:o,to:Math.max(a,o+1)}}function Nr(e,t){var n=e.display,r=rr(e.display);t.top<0&&(t.top=0);var i=e.curOp&&null!=e.curOp.scrollTop?e.curOp.scrollTop:n.scroller.scrollTop,o=On(e),a={};t.bottom-t.top>o&&(t.bottom=t.top+o);var l=e.doc.height+Sn(n),s=t.top<r,c=t.bottom>l-r;if(t.top<i)a.scrollTop=s?0:t.top;else if(t.bottom>i+o){var u=Math.min(t.top,(c?l:t.bottom)-o);u!=i&&(a.scrollTop=u)}var f=e.curOp&&null!=e.curOp.scrollLeft?e.curOp.scrollLeft:n.scroller.scrollLeft,d=Mn(e)-(e.options.fixedGutter?n.gutters.offsetWidth:0),h=t.right-t.left>d;return h&&(t.right=t.left+d),t.left<10?a.scrollLeft=0:t.left<f?a.scrollLeft=Math.max(0,t.left-(h?0:10)):t.right>d+f-3&&(a.scrollLeft=t.right+(h?0:10)-d),a}function Ar(e,t){null!=t&&(Pr(e),e.curOp.scrollTop=(null==e.curOp.scrollTop?e.doc.scrollTop:e.curOp.scrollTop)+t)}function Er(e){Pr(e);var t=e.getCursor();e.curOp.scrollToPos={from:t,to:t,margin:e.options.cursorScrollMargin}}function zr(e,t,n){null==t&&null==n||Pr(e),null!=t&&(e.curOp.scrollLeft=t),null!=n&&(e.curOp.scrollTop=n)}function Pr(e){var t=e.curOp.scrollToPos;t&&(e.curOp.scrollToPos=null,Dr(e,Gn(e,t.from),Gn(e,t.to),t.margin))}function Dr(e,t,n,r){var i=Nr(e,{left:Math.min(t.left,n.left),top:Math.min(t.top,n.top)-r,right:Math.max(t.right,n.right),bottom:Math.max(t.bottom,n.bottom)+r});zr(e,i.scrollLeft,i.scrollTop)}function Ir(e,t){Math.abs(e.doc.scrollTop-t)<2||(n||si(e,{top:t}),Fr(e,t,!0),n&&si(e),ri(e,100))}function Fr(e,t,n){t=Math.max(0,Math.min(e.display.scroller.scrollHeight-e.display.scroller.clientHeight,t)),(e.display.scroller.scrollTop!=t||n)&&(e.doc.scrollTop=t,e.display.scrollbars.setScrollTop(t),e.display.scroller.scrollTop!=t&&(e.display.scroller.scrollTop=t))}function _r(e,t,n,r){t=Math.max(0,Math.min(t,e.display.scroller.scrollWidth-e.display.scroller.clientWidth)),(n?t==e.doc.scrollLeft:Math.abs(e.doc.scrollLeft-t)<2)&&!r||(e.doc.scrollLeft=t,fi(e),e.display.scroller.scrollLeft!=t&&(e.display.scroller.scrollLeft=t),e.display.scrollbars.setScrollLeft(t))}function Wr(e){var t=e.display,n=t.gutters.offsetWidth,r=Math.round(e.doc.height+Sn(e.display));return{clientHeight:t.scroller.clientHeight,viewHeight:t.wrapper.clientHeight,scrollWidth:t.scroller.scrollWidth,clientWidth:t.scroller.clientWidth,viewWidth:t.wrapper.clientWidth,barLeft:e.options.fixedGutter?n:0,docHeight:r,scrollHeight:r+Ln(e)+t.barHeight,nativeBarWidth:t.nativeBarWidth,gutterWidth:n}}var Hr=function(e,t,n){this.cm=n;var r=this.vert=N("div",[N("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),i=this.horiz=N("div",[N("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");r.tabIndex=i.tabIndex=-1,e(r),e(i),fe(r,"scroll",(function(){r.clientHeight&&t(r.scrollTop,"vertical")})),fe(i,"scroll",(function(){i.clientWidth&&t(i.scrollLeft,"horizontal")})),this.checkedZeroWidth=!1,a&&l<8&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")};Hr.prototype.update=function(e){var t=e.scrollWidth>e.clientWidth+1,n=e.scrollHeight>e.clientHeight+1,r=e.nativeBarWidth;if(n){this.vert.style.display="block",this.vert.style.bottom=t?r+"px":"0";var i=e.viewHeight-(t?r:0);this.vert.firstChild.style.height=Math.max(0,e.scrollHeight-e.clientHeight+i)+"px"}else this.vert.style.display="",this.vert.firstChild.style.height="0";if(t){this.horiz.style.display="block",this.horiz.style.right=n?r+"px":"0",this.horiz.style.left=e.barLeft+"px";var o=e.viewWidth-e.barLeft-(n?r:0);this.horiz.firstChild.style.width=Math.max(0,e.scrollWidth-e.clientWidth+o)+"px"}else this.horiz.style.display="",this.horiz.firstChild.style.width="0";return!this.checkedZeroWidth&&e.clientHeight>0&&(0==r&&this.zeroWidthHack(),this.checkedZeroWidth=!0),{right:n?r:0,bottom:t?r:0}},Hr.prototype.setScrollLeft=function(e){this.horiz.scrollLeft!=e&&(this.horiz.scrollLeft=e),this.disableHoriz&&this.enableZeroWidthBar(this.horiz,this.disableHoriz,"horiz")},Hr.prototype.setScrollTop=function(e){this.vert.scrollTop!=e&&(this.vert.scrollTop=e),this.disableVert&&this.enableZeroWidthBar(this.vert,this.disableVert,"vert")},Hr.prototype.zeroWidthHack=function(){var e=y&&!h?"12px":"18px";this.horiz.style.height=this.vert.style.width=e,this.horiz.style.pointerEvents=this.vert.style.pointerEvents="none",this.disableHoriz=new H,this.disableVert=new H},Hr.prototype.enableZeroWidthBar=function(e,t,n){e.style.pointerEvents="auto",t.set(1e3,(function r(){var i=e.getBoundingClientRect();("vert"==n?document.elementFromPoint(i.right-1,(i.top+i.bottom)/2):document.elementFromPoint((i.right+i.left)/2,i.bottom-1))!=e?e.style.pointerEvents="none":t.set(1e3,r)}))},Hr.prototype.clear=function(){var e=this.horiz.parentNode;e.removeChild(this.horiz),e.removeChild(this.vert)};var Rr=function(){};function Br(e,t){t||(t=Wr(e));var n=e.display.barWidth,r=e.display.barHeight;jr(e,t);for(var i=0;i<4&&n!=e.display.barWidth||r!=e.display.barHeight;i++)n!=e.display.barWidth&&e.options.lineWrapping&&Lr(e),jr(e,Wr(e)),n=e.display.barWidth,r=e.display.barHeight}function jr(e,t){var n=e.display,r=n.scrollbars.update(t);n.sizer.style.paddingRight=(n.barWidth=r.right)+"px",n.sizer.style.paddingBottom=(n.barHeight=r.bottom)+"px",n.heightForcer.style.borderBottom=r.bottom+"px solid transparent",r.right&&r.bottom?(n.scrollbarFiller.style.display="block",n.scrollbarFiller.style.height=r.bottom+"px",n.scrollbarFiller.style.width=r.right+"px"):n.scrollbarFiller.style.display="",r.bottom&&e.options.coverGutterNextToScrollbar&&e.options.fixedGutter?(n.gutterFiller.style.display="block",n.gutterFiller.style.height=r.bottom+"px",n.gutterFiller.style.width=t.gutterWidth+"px"):n.gutterFiller.style.display=""}Rr.prototype.update=function(){return{bottom:0,right:0}},Rr.prototype.setScrollLeft=function(){},Rr.prototype.setScrollTop=function(){},Rr.prototype.clear=function(){};var qr={native:Hr,null:Rr};function Ur(e){e.display.scrollbars&&(e.display.scrollbars.clear(),e.display.scrollbars.addClass&&L(e.display.wrapper,e.display.scrollbars.addClass)),e.display.scrollbars=new qr[e.options.scrollbarStyle]((function(t){e.display.wrapper.insertBefore(t,e.display.scrollbarFiller),fe(t,"mousedown",(function(){e.state.focused&&setTimeout((function(){return e.display.input.focus()}),0)})),t.setAttribute("cm-not-content","true")}),(function(t,n){"horizontal"==n?_r(e,t):Ir(e,t)}),e),e.display.scrollbars.addClass&&P(e.display.wrapper,e.display.scrollbars.addClass)}var Vr=0;function Kr(e){var t;e.curOp={cm:e,viewChanged:!1,startHeight:e.doc.height,forceUpdate:!1,updateInput:0,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,focus:!1,id:++Vr},t=e.curOp,an?an.ops.push(t):t.ownsGroup=an={ops:[t],delayedCallbacks:[]}}function $r(e){var t=e.curOp;t&&function(e,t){var n=e.ownsGroup;if(n)try{!function(e){var t=e.delayedCallbacks,n=0;do{for(;n<t.length;n++)t[n].call(null);for(var r=0;r<e.ops.length;r++){var i=e.ops[r];if(i.cursorActivityHandlers)for(;i.cursorActivityCalled<i.cursorActivityHandlers.length;)i.cursorActivityHandlers[i.cursorActivityCalled++].call(null,i.cm)}}while(n<t.length)}(n)}finally{an=null,t(n)}}(t,(function(e){for(var t=0;t<e.ops.length;t++)e.ops[t].cm.curOp=null;!function(e){for(var t=e.ops,n=0;n<t.length;n++)Gr(t[n]);for(var r=0;r<t.length;r++)Xr(t[r]);for(var i=0;i<t.length;i++)Zr(t[i]);for(var o=0;o<t.length;o++)Yr(t[o]);for(var a=0;a<t.length;a++)Qr(t[a])}(e)}))}function Gr(e){var t=e.cm,n=t.display;!function(e){var t=e.display;!t.scrollbarsClipped&&t.scroller.offsetWidth&&(t.nativeBarWidth=t.scroller.offsetWidth-t.scroller.clientWidth,t.heightForcer.style.height=Ln(e)+"px",t.sizer.style.marginBottom=-t.nativeBarWidth+"px",t.sizer.style.borderRightWidth=Ln(e)+"px",t.scrollbarsClipped=!0)}(t),e.updateMaxLine&&Vt(t),e.mustUpdate=e.viewChanged||e.forceUpdate||null!=e.scrollTop||e.scrollToPos&&(e.scrollToPos.from.line<n.viewFrom||e.scrollToPos.to.line>=n.viewTo)||n.maxLineChanged&&t.options.lineWrapping,e.update=e.mustUpdate&&new oi(t,e.mustUpdate&&{top:e.scrollTop,ensure:e.scrollToPos},e.forceUpdate)}function Xr(e){e.updatedDisplay=e.mustUpdate&&ai(e.cm,e.update)}function Zr(e){var t=e.cm,n=t.display;e.updatedDisplay&&Lr(t),e.barMeasure=Wr(t),n.maxLineChanged&&!t.options.lineWrapping&&(e.adjustWidthTo=An(t,n.maxLine,n.maxLine.text.length).left+3,t.display.sizerWidth=e.adjustWidthTo,e.barMeasure.scrollWidth=Math.max(n.scroller.clientWidth,n.sizer.offsetLeft+e.adjustWidthTo+Ln(t)+t.display.barWidth),e.maxScrollLeft=Math.max(0,n.sizer.offsetLeft+e.adjustWidthTo-Mn(t))),(e.updatedDisplay||e.selectionChanged)&&(e.preparedSelection=n.input.prepareSelection())}function Yr(e){var t=e.cm;null!=e.adjustWidthTo&&(t.display.sizer.style.minWidth=e.adjustWidthTo+"px",e.maxScrollLeft<t.doc.scrollLeft&&_r(t,Math.min(t.display.scroller.scrollLeft,e.maxScrollLeft),!0),t.display.maxLineChanged=!1);var n=e.focus&&e.focus==z();e.preparedSelection&&t.display.input.showSelection(e.preparedSelection,n),(e.updatedDisplay||e.startHeight!=t.doc.height)&&Br(t,e.barMeasure),e.updatedDisplay&&ui(t,e.barMeasure),e.selectionChanged&&wr(t),t.state.focused&&e.updateInput&&t.display.input.reset(e.typing),n&&kr(e.cm)}function Qr(e){var t=e.cm,n=t.display,r=t.doc;e.updatedDisplay&&li(t,e.update),null==n.wheelStartX||null==e.scrollTop&&null==e.scrollLeft&&!e.scrollToPos||(n.wheelStartX=n.wheelStartY=null),null!=e.scrollTop&&Fr(t,e.scrollTop,e.forceScroll),null!=e.scrollLeft&&_r(t,e.scrollLeft,!0,!0),e.scrollToPos&&function(e,t){if(!me(e,"scrollCursorIntoView")){var n=e.display,r=n.sizer.getBoundingClientRect(),i=null;if(t.top+r.top<0?i=!0:t.bottom+r.top>(window.innerHeight||document.documentElement.clientHeight)&&(i=!1),null!=i&&!p){var o=N("div","​",null,"position: absolute;\n top: "+(t.top-n.viewOffset-Cn(e.display))+"px;\n height: "+(t.bottom-t.top+Ln(e)+n.barHeight)+"px;\n left: "+t.left+"px; width: "+Math.max(2,t.right-t.left)+"px;");e.display.lineSpace.appendChild(o),o.scrollIntoView(i),e.display.lineSpace.removeChild(o)}}}(t,function(e,t,n,r){var i;null==r&&(r=0),e.options.lineWrapping||t!=n||(n="before"==(t=t.ch?et(t.line,"before"==t.sticky?t.ch-1:t.ch,"after"):t).sticky?et(t.line,t.ch+1,"before"):t);for(var o=0;o<5;o++){var a=!1,l=$n(e,t),s=n&&n!=t?$n(e,n):l,c=Nr(e,i={left:Math.min(l.left,s.left),top:Math.min(l.top,s.top)-r,right:Math.max(l.left,s.left),bottom:Math.max(l.bottom,s.bottom)+r}),u=e.doc.scrollTop,f=e.doc.scrollLeft;if(null!=c.scrollTop&&(Ir(e,c.scrollTop),Math.abs(e.doc.scrollTop-u)>1&&(a=!0)),null!=c.scrollLeft&&(_r(e,c.scrollLeft),Math.abs(e.doc.scrollLeft-f)>1&&(a=!0)),!a)break}return i}(t,lt(r,e.scrollToPos.from),lt(r,e.scrollToPos.to),e.scrollToPos.margin));var i=e.maybeHiddenMarkers,o=e.maybeUnhiddenMarkers;if(i)for(var a=0;a<i.length;++a)i[a].lines.length||pe(i[a],"hide");if(o)for(var l=0;l<o.length;++l)o[l].lines.length&&pe(o[l],"unhide");n.wrapper.offsetHeight&&(r.scrollTop=t.display.scroller.scrollTop),e.changeObjs&&pe(t,"changes",t,e.changeObjs),e.update&&e.update.finish()}function Jr(e,t){if(e.curOp)return t();Kr(e);try{return t()}finally{$r(e)}}function ei(e,t){return function(){if(e.curOp)return t.apply(e,arguments);Kr(e);try{return t.apply(e,arguments)}finally{$r(e)}}}function ti(e){return function(){if(this.curOp)return e.apply(this,arguments);Kr(this);try{return e.apply(this,arguments)}finally{$r(this)}}}function ni(e){return function(){var t=this.cm;if(!t||t.curOp)return e.apply(this,arguments);Kr(t);try{return e.apply(this,arguments)}finally{$r(t)}}}function ri(e,t){e.doc.highlightFrontier<e.display.viewTo&&e.state.highlight.set(t,F(ii,e))}function ii(e){var t=e.doc;if(!(t.highlightFrontier>=e.display.viewTo)){var n=+new Date+e.options.workTime,r=ht(e,t.highlightFrontier),i=[];t.iter(r.line,Math.min(t.first+t.size,e.display.viewTo+500),(function(o){if(r.line>=e.display.viewFrom){var a=o.styles,l=o.text.length>e.options.maxHighlightLength?je(t.mode,r.state):null,s=ft(e,o,r,!0);l&&(r.state=l),o.styles=s.styles;var c=o.styleClasses,u=s.classes;u?o.styleClasses=u:c&&(o.styleClasses=null);for(var f=!a||a.length!=o.styles.length||c!=u&&(!c||!u||c.bgClass!=u.bgClass||c.textClass!=u.textClass),d=0;!f&&d<a.length;++d)f=a[d]!=o.styles[d];f&&i.push(r.line),o.stateAfter=r.save(),r.nextLine()}else o.text.length<=e.options.maxHighlightLength&&pt(e,o.text,r),o.stateAfter=r.line%5==0?r.save():null,r.nextLine();if(+new Date>n)return ri(e,e.options.workDelay),!0})),t.highlightFrontier=r.line,t.modeFrontier=Math.max(t.modeFrontier,r.line),i.length&&Jr(e,(function(){for(var t=0;t<i.length;t++)dr(e,i[t],"text")}))}}var oi=function(e,t,n){var r=e.display;this.viewport=t,this.visible=Or(r,e.doc,t),this.editorIsHidden=!r.wrapper.offsetWidth,this.wrapperHeight=r.wrapper.clientHeight,this.wrapperWidth=r.wrapper.clientWidth,this.oldDisplayWidth=Mn(e),this.force=n,this.dims=or(e),this.events=[]};function ai(e,t){var n=e.display,r=e.doc;if(t.editorIsHidden)return hr(e),!1;if(!t.force&&t.visible.from>=n.viewFrom&&t.visible.to<=n.viewTo&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo)&&n.renderedView==n.view&&0==mr(e))return!1;di(e)&&(hr(e),t.dims=or(e));var i=r.first+r.size,o=Math.max(t.visible.from-e.options.viewportMargin,r.first),a=Math.min(i,t.visible.to+e.options.viewportMargin);n.viewFrom<o&&o-n.viewFrom<20&&(o=Math.max(r.first,n.viewFrom)),n.viewTo>a&&n.viewTo-a<20&&(a=Math.min(i,n.viewTo)),kt&&(o=Ht(e.doc,o),a=Rt(e.doc,a));var l=o!=n.viewFrom||a!=n.viewTo||n.lastWrapHeight!=t.wrapperHeight||n.lastWrapWidth!=t.wrapperWidth;!function(e,t,n){var r=e.display;0==r.view.length||t>=r.viewTo||n<=r.viewFrom?(r.view=on(e,t,n),r.viewFrom=t):(r.viewFrom>t?r.view=on(e,t,r.viewFrom).concat(r.view):r.viewFrom<t&&(r.view=r.view.slice(ur(e,t))),r.viewFrom=t,r.viewTo<n?r.view=r.view.concat(on(e,r.viewTo,n)):r.viewTo>n&&(r.view=r.view.slice(0,ur(e,n)))),r.viewTo=n}(e,o,a),n.viewOffset=qt(Ke(e.doc,n.viewFrom)),e.display.mover.style.top=n.viewOffset+"px";var c=mr(e);if(!l&&0==c&&!t.force&&n.renderedView==n.view&&(null==n.updateLineNumbers||n.updateLineNumbers>=n.viewTo))return!1;var u=function(e){if(e.hasFocus())return null;var t=z();if(!t||!E(e.display.lineDiv,t))return null;var n={activeElt:t};if(window.getSelection){var r=window.getSelection();r.anchorNode&&r.extend&&E(e.display.lineDiv,r.anchorNode)&&(n.anchorNode=r.anchorNode,n.anchorOffset=r.anchorOffset,n.focusNode=r.focusNode,n.focusOffset=r.focusOffset)}return n}(e);return c>4&&(n.lineDiv.style.display="none"),function(e,t,n){var r=e.display,i=e.options.lineNumbers,o=r.lineDiv,a=o.firstChild;function l(t){var n=t.nextSibling;return s&&y&&e.display.currentWheelTarget==t?t.style.display="none":t.parentNode.removeChild(t),n}for(var c=r.view,u=r.viewFrom,f=0;f<c.length;f++){var d=c[f];if(d.hidden);else if(d.node&&d.node.parentNode==o){for(;a!=d.node;)a=l(a);var h=i&&null!=t&&t<=u&&d.lineNumber;d.changes&&(R(d.changes,"gutter")>-1&&(h=!1),un(e,d,u,n)),h&&(M(d.lineNumber),d.lineNumber.appendChild(document.createTextNode(Je(e.options,u)))),a=d.node.nextSibling}else{var p=vn(e,d,u,n);o.insertBefore(p,a)}u+=d.size}for(;a;)a=l(a)}(e,n.updateLineNumbers,t.dims),c>4&&(n.lineDiv.style.display=""),n.renderedView=n.view,function(e){if(e&&e.activeElt&&e.activeElt!=z()&&(e.activeElt.focus(),!/^(INPUT|TEXTAREA)$/.test(e.activeElt.nodeName)&&e.anchorNode&&E(document.body,e.anchorNode)&&E(document.body,e.focusNode))){var t=window.getSelection(),n=document.createRange();n.setEnd(e.anchorNode,e.anchorOffset),n.collapse(!1),t.removeAllRanges(),t.addRange(n),t.extend(e.focusNode,e.focusOffset)}}(u),M(n.cursorDiv),M(n.selectionDiv),n.gutters.style.height=n.sizer.style.minHeight=0,l&&(n.lastWrapHeight=t.wrapperHeight,n.lastWrapWidth=t.wrapperWidth,ri(e,400)),n.updateLineNumbers=null,!0}function li(e,t){for(var n=t.viewport,r=!0;;r=!1){if(r&&e.options.lineWrapping&&t.oldDisplayWidth!=Mn(e))r&&(t.visible=Or(e.display,e.doc,n));else if(n&&null!=n.top&&(n={top:Math.min(e.doc.height+Sn(e.display)-On(e),n.top)}),t.visible=Or(e.display,e.doc,n),t.visible.from>=e.display.viewFrom&&t.visible.to<=e.display.viewTo)break;if(!ai(e,t))break;Lr(e);var i=Wr(e);gr(e),Br(e,i),ui(e,i),t.force=!1}t.signal(e,"update",e),e.display.viewFrom==e.display.reportedViewFrom&&e.display.viewTo==e.display.reportedViewTo||(t.signal(e,"viewportChange",e,e.display.viewFrom,e.display.viewTo),e.display.reportedViewFrom=e.display.viewFrom,e.display.reportedViewTo=e.display.viewTo)}function si(e,t){var n=new oi(e,t);if(ai(e,n)){Lr(e),li(e,n);var r=Wr(e);gr(e),Br(e,r),ui(e,r),n.finish()}}function ci(e){var t=e.gutters.offsetWidth;e.sizer.style.marginLeft=t+"px"}function ui(e,t){e.display.sizer.style.minHeight=t.docHeight+"px",e.display.heightForcer.style.top=t.docHeight+"px",e.display.gutters.style.height=t.docHeight+e.display.barHeight+Ln(e)+"px"}function fi(e){var t=e.display,n=t.view;if(t.alignWidgets||t.gutters.firstChild&&e.options.fixedGutter){for(var r=ar(t)-t.scroller.scrollLeft+e.doc.scrollLeft,i=t.gutters.offsetWidth,o=r+"px",a=0;a<n.length;a++)if(!n[a].hidden){e.options.fixedGutter&&(n[a].gutter&&(n[a].gutter.style.left=o),n[a].gutterBackground&&(n[a].gutterBackground.style.left=o));var l=n[a].alignable;if(l)for(var s=0;s<l.length;s++)l[s].style.left=o}e.options.fixedGutter&&(t.gutters.style.left=r+i+"px")}}function di(e){if(!e.options.lineNumbers)return!1;var t=e.doc,n=Je(e.options,t.first+t.size-1),r=e.display;if(n.length!=r.lineNumChars){var i=r.measure.appendChild(N("div",[N("div",n)],"CodeMirror-linenumber CodeMirror-gutter-elt")),o=i.firstChild.offsetWidth,a=i.offsetWidth-o;return r.lineGutter.style.width="",r.lineNumInnerWidth=Math.max(o,r.lineGutter.offsetWidth-a)+1,r.lineNumWidth=r.lineNumInnerWidth+a,r.lineNumChars=r.lineNumInnerWidth?n.length:-1,r.lineGutter.style.width=r.lineNumWidth+"px",ci(e.display),!0}return!1}function hi(e,t){for(var n=[],r=!1,i=0;i<e.length;i++){var o=e[i],a=null;if("string"!=typeof o&&(a=o.style,o=o.className),"CodeMirror-linenumbers"==o){if(!t)continue;r=!0}n.push({className:o,style:a})}return t&&!r&&n.push({className:"CodeMirror-linenumbers",style:null}),n}function pi(e){var t=e.gutters,n=e.gutterSpecs;M(t),e.lineGutter=null;for(var r=0;r<n.length;++r){var i=n[r],o=i.className,a=i.style,l=t.appendChild(N("div",null,"CodeMirror-gutter "+o));a&&(l.style.cssText=a),"CodeMirror-linenumbers"==o&&(e.lineGutter=l,l.style.width=(e.lineNumWidth||1)+"px")}t.style.display=n.length?"":"none",ci(e)}function mi(e){pi(e.display),fr(e),fi(e)}function gi(e,t,r,i){var o=this;this.input=r,o.scrollbarFiller=N("div",null,"CodeMirror-scrollbar-filler"),o.scrollbarFiller.setAttribute("cm-not-content","true"),o.gutterFiller=N("div",null,"CodeMirror-gutter-filler"),o.gutterFiller.setAttribute("cm-not-content","true"),o.lineDiv=A("div",null,"CodeMirror-code"),o.selectionDiv=N("div",null,null,"position: relative; z-index: 1"),o.cursorDiv=N("div",null,"CodeMirror-cursors"),o.measure=N("div",null,"CodeMirror-measure"),o.lineMeasure=N("div",null,"CodeMirror-measure"),o.lineSpace=A("div",[o.measure,o.lineMeasure,o.selectionDiv,o.cursorDiv,o.lineDiv],null,"position: relative; outline: none");var c=A("div",[o.lineSpace],"CodeMirror-lines");o.mover=N("div",[c],null,"position: relative"),o.sizer=N("div",[o.mover],"CodeMirror-sizer"),o.sizerWidth=null,o.heightForcer=N("div",null,null,"position: absolute; height: 50px; width: 1px;"),o.gutters=N("div",null,"CodeMirror-gutters"),o.lineGutter=null,o.scroller=N("div",[o.sizer,o.heightForcer,o.gutters],"CodeMirror-scroll"),o.scroller.setAttribute("tabIndex","-1"),o.wrapper=N("div",[o.scrollbarFiller,o.gutterFiller,o.scroller],"CodeMirror"),a&&l<8&&(o.gutters.style.zIndex=-1,o.scroller.style.paddingRight=0),s||n&&v||(o.scroller.draggable=!0),e&&(e.appendChild?e.appendChild(o.wrapper):e(o.wrapper)),o.viewFrom=o.viewTo=t.first,o.reportedViewFrom=o.reportedViewTo=t.first,o.view=[],o.renderedView=null,o.externalMeasured=null,o.viewOffset=0,o.lastWrapHeight=o.lastWrapWidth=0,o.updateLineNumbers=null,o.nativeBarWidth=o.barHeight=o.barWidth=0,o.scrollbarsClipped=!1,o.lineNumWidth=o.lineNumInnerWidth=o.lineNumChars=null,o.alignWidgets=!1,o.cachedCharWidth=o.cachedTextHeight=o.cachedPaddingH=null,o.maxLine=null,o.maxLineLength=0,o.maxLineChanged=!1,o.wheelDX=o.wheelDY=o.wheelStartX=o.wheelStartY=null,o.shift=!1,o.selForContextMenu=null,o.activeTouch=null,o.gutterSpecs=hi(i.gutters,i.lineNumbers),pi(o),r.init(o)}oi.prototype.signal=function(e,t){ve(e,t)&&this.events.push(arguments)},oi.prototype.finish=function(){for(var e=0;e<this.events.length;e++)pe.apply(null,this.events[e])};var vi=0,yi=null;function bi(e){var t=e.wheelDeltaX,n=e.wheelDeltaY;return null==t&&e.detail&&e.axis==e.HORIZONTAL_AXIS&&(t=e.detail),null==n&&e.detail&&e.axis==e.VERTICAL_AXIS?n=e.detail:null==n&&(n=e.wheelDelta),{x:t,y:n}}function xi(e){var t=bi(e);return t.x*=yi,t.y*=yi,t}function wi(e,t){var r=bi(t),i=r.x,o=r.y,a=e.display,l=a.scroller,c=l.scrollWidth>l.clientWidth,u=l.scrollHeight>l.clientHeight;if(i&&c||o&&u){if(o&&y&&s)e:for(var d=t.target,h=a.view;d!=l;d=d.parentNode)for(var p=0;p<h.length;p++)if(h[p].node==d){e.display.currentWheelTarget=d;break e}if(i&&!n&&!f&&null!=yi)return o&&u&&Ir(e,Math.max(0,l.scrollTop+o*yi)),_r(e,Math.max(0,l.scrollLeft+i*yi)),(!o||o&&u)&&be(t),void(a.wheelStartX=null);if(o&&null!=yi){var m=o*yi,g=e.doc.scrollTop,v=g+a.wrapper.clientHeight;m<0?g=Math.max(0,g+m-50):v=Math.min(e.doc.height,v+m+50),si(e,{top:g,bottom:v})}vi<20&&(null==a.wheelStartX?(a.wheelStartX=l.scrollLeft,a.wheelStartY=l.scrollTop,a.wheelDX=i,a.wheelDY=o,setTimeout((function(){if(null!=a.wheelStartX){var e=l.scrollLeft-a.wheelStartX,t=l.scrollTop-a.wheelStartY,n=t&&a.wheelDY&&t/a.wheelDY||e&&a.wheelDX&&e/a.wheelDX;a.wheelStartX=a.wheelStartY=null,n&&(yi=(yi*vi+n)/(vi+1),++vi)}}),200)):(a.wheelDX+=i,a.wheelDY+=o))}}a?yi=-.53:n?yi=15:u?yi=-.7:d&&(yi=-1/3);var ki=function(e,t){this.ranges=e,this.primIndex=t};ki.prototype.primary=function(){return this.ranges[this.primIndex]},ki.prototype.equals=function(e){if(e==this)return!0;if(e.primIndex!=this.primIndex||e.ranges.length!=this.ranges.length)return!1;for(var t=0;t<this.ranges.length;t++){var n=this.ranges[t],r=e.ranges[t];if(!nt(n.anchor,r.anchor)||!nt(n.head,r.head))return!1}return!0},ki.prototype.deepCopy=function(){for(var e=[],t=0;t<this.ranges.length;t++)e[t]=new Ci(rt(this.ranges[t].anchor),rt(this.ranges[t].head));return new ki(e,this.primIndex)},ki.prototype.somethingSelected=function(){for(var e=0;e<this.ranges.length;e++)if(!this.ranges[e].empty())return!0;return!1},ki.prototype.contains=function(e,t){t||(t=e);for(var n=0;n<this.ranges.length;n++){var r=this.ranges[n];if(tt(t,r.from())>=0&&tt(e,r.to())<=0)return n}return-1};var Ci=function(e,t){this.anchor=e,this.head=t};function Si(e,t,n){var r=e&&e.options.selectionsMayTouch,i=t[n];t.sort((function(e,t){return tt(e.from(),t.from())})),n=R(t,i);for(var o=1;o<t.length;o++){var a=t[o],l=t[o-1],s=tt(l.to(),a.from());if(r&&!a.empty()?s>0:s>=0){var c=ot(l.from(),a.from()),u=it(l.to(),a.to()),f=l.empty()?a.from()==a.head:l.from()==l.head;o<=n&&--n,t.splice(--o,2,new Ci(f?u:c,f?c:u))}}return new ki(t,n)}function Ti(e,t){return new ki([new Ci(e,t||e)],0)}function Li(e){return e.text?et(e.from.line+e.text.length-1,G(e.text).length+(1==e.text.length?e.from.ch:0)):e.to}function Mi(e,t){if(tt(e,t.from)<0)return e;if(tt(e,t.to)<=0)return Li(t);var n=e.line+t.text.length-(t.to.line-t.from.line)-1,r=e.ch;return e.line==t.to.line&&(r+=Li(t).ch-t.to.ch),et(n,r)}function Oi(e,t){for(var n=[],r=0;r<e.sel.ranges.length;r++){var i=e.sel.ranges[r];n.push(new Ci(Mi(i.anchor,t),Mi(i.head,t)))}return Si(e.cm,n,e.sel.primIndex)}function Ni(e,t,n){return e.line==t.line?et(n.line,e.ch-t.ch+n.ch):et(n.line+(e.line-t.line),e.ch)}function Ai(e){e.doc.mode=He(e.options,e.doc.modeOption),Ei(e)}function Ei(e){e.doc.iter((function(e){e.stateAfter&&(e.stateAfter=null),e.styles&&(e.styles=null)})),e.doc.modeFrontier=e.doc.highlightFrontier=e.doc.first,ri(e,100),e.state.modeGen++,e.curOp&&fr(e)}function zi(e,t){return 0==t.from.ch&&0==t.to.ch&&""==G(t.text)&&(!e.cm||e.cm.options.wholeLineUpdateBefore)}function Pi(e,t,n,r){function i(e){return n?n[e]:null}function o(e,n,i){!function(e,t,n,r){e.text=t,e.stateAfter&&(e.stateAfter=null),e.styles&&(e.styles=null),null!=e.order&&(e.order=null),Ot(e),Nt(e,n);var i=r?r(e):1;i!=e.height&&Xe(e,i)}(e,n,i,r),sn(e,"change",e,t)}function a(e,t){for(var n=[],o=e;o<t;++o)n.push(new Kt(c[o],i(o),r));return n}var l=t.from,s=t.to,c=t.text,u=Ke(e,l.line),f=Ke(e,s.line),d=G(c),h=i(c.length-1),p=s.line-l.line;if(t.full)e.insert(0,a(0,c.length)),e.remove(c.length,e.size-c.length);else if(zi(e,t)){var m=a(0,c.length-1);o(f,f.text,h),p&&e.remove(l.line,p),m.length&&e.insert(l.line,m)}else if(u==f)if(1==c.length)o(u,u.text.slice(0,l.ch)+d+u.text.slice(s.ch),h);else{var g=a(1,c.length-1);g.push(new Kt(d+u.text.slice(s.ch),h,r)),o(u,u.text.slice(0,l.ch)+c[0],i(0)),e.insert(l.line+1,g)}else if(1==c.length)o(u,u.text.slice(0,l.ch)+c[0]+f.text.slice(s.ch),i(0)),e.remove(l.line+1,p);else{o(u,u.text.slice(0,l.ch)+c[0],i(0)),o(f,d+f.text.slice(s.ch),h);var v=a(1,c.length-1);p>1&&e.remove(l.line+1,p-1),e.insert(l.line+1,v)}sn(e,"change",e,t)}function Di(e,t,n){!function e(r,i,o){if(r.linked)for(var a=0;a<r.linked.length;++a){var l=r.linked[a];if(l.doc!=i){var s=o&&l.sharedHist;n&&!s||(t(l.doc,s),e(l.doc,r,s))}}}(e,null,!0)}function Ii(e,t){if(t.cm)throw new Error("This document is already in use.");e.doc=t,t.cm=e,sr(e),Ai(e),Fi(e),e.options.lineWrapping||Vt(e),e.options.mode=t.modeOption,fr(e)}function Fi(e){("rtl"==e.doc.direction?P:L)(e.display.lineDiv,"CodeMirror-rtl")}function _i(e){this.done=[],this.undone=[],this.undoDepth=1/0,this.lastModTime=this.lastSelTime=0,this.lastOp=this.lastSelOp=null,this.lastOrigin=this.lastSelOrigin=null,this.generation=this.maxGeneration=e||1}function Wi(e,t){var n={from:rt(t.from),to:Li(t),text:$e(e,t.from,t.to)};return qi(e,n,t.from.line,t.to.line+1),Di(e,(function(e){return qi(e,n,t.from.line,t.to.line+1)}),!0),n}function Hi(e){for(;e.length&&G(e).ranges;)e.pop()}function Ri(e,t,n,r){var i=e.history;i.undone.length=0;var o,a,l=+new Date;if((i.lastOp==r||i.lastOrigin==t.origin&&t.origin&&("+"==t.origin.charAt(0)&&i.lastModTime>l-(e.cm?e.cm.options.historyEventDelay:500)||"*"==t.origin.charAt(0)))&&(o=function(e,t){return t?(Hi(e.done),G(e.done)):e.done.length&&!G(e.done).ranges?G(e.done):e.done.length>1&&!e.done[e.done.length-2].ranges?(e.done.pop(),G(e.done)):void 0}(i,i.lastOp==r)))a=G(o.changes),0==tt(t.from,t.to)&&0==tt(t.from,a.to)?a.to=Li(t):o.changes.push(Wi(e,t));else{var s=G(i.done);for(s&&s.ranges||ji(e.sel,i.done),o={changes:[Wi(e,t)],generation:i.generation},i.done.push(o);i.done.length>i.undoDepth;)i.done.shift(),i.done[0].ranges||i.done.shift()}i.done.push(n),i.generation=++i.maxGeneration,i.lastModTime=i.lastSelTime=l,i.lastOp=i.lastSelOp=r,i.lastOrigin=i.lastSelOrigin=t.origin,a||pe(e,"historyAdded")}function Bi(e,t,n,r){var i=e.history,o=r&&r.origin;n==i.lastSelOp||o&&i.lastSelOrigin==o&&(i.lastModTime==i.lastSelTime&&i.lastOrigin==o||function(e,t,n,r){var i=t.charAt(0);return"*"==i||"+"==i&&n.ranges.length==r.ranges.length&&n.somethingSelected()==r.somethingSelected()&&new Date-e.history.lastSelTime<=(e.cm?e.cm.options.historyEventDelay:500)}(e,o,G(i.done),t))?i.done[i.done.length-1]=t:ji(t,i.done),i.lastSelTime=+new Date,i.lastSelOrigin=o,i.lastSelOp=n,r&&!1!==r.clearRedo&&Hi(i.undone)}function ji(e,t){var n=G(t);n&&n.ranges&&n.equals(e)||t.push(e)}function qi(e,t,n,r){var i=t["spans_"+e.id],o=0;e.iter(Math.max(e.first,n),Math.min(e.first+e.size,r),(function(n){n.markedSpans&&((i||(i=t["spans_"+e.id]={}))[o]=n.markedSpans),++o}))}function Ui(e){if(!e)return null;for(var t,n=0;n<e.length;++n)e[n].marker.explicitlyCleared?t||(t=e.slice(0,n)):t&&t.push(e[n]);return t?t.length?t:null:e}function Vi(e,t){var n=function(e,t){var n=t["spans_"+e.id];if(!n)return null;for(var r=[],i=0;i<t.text.length;++i)r.push(Ui(n[i]));return r}(e,t),r=Lt(e,t);if(!n)return r;if(!r)return n;for(var i=0;i<n.length;++i){var o=n[i],a=r[i];if(o&&a)e:for(var l=0;l<a.length;++l){for(var s=a[l],c=0;c<o.length;++c)if(o[c].marker==s.marker)continue e;o.push(s)}else a&&(n[i]=a)}return n}function Ki(e,t,n){for(var r=[],i=0;i<e.length;++i){var o=e[i];if(o.ranges)r.push(n?ki.prototype.deepCopy.call(o):o);else{var a=o.changes,l=[];r.push({changes:l});for(var s=0;s<a.length;++s){var c=a[s],u=void 0;if(l.push({from:c.from,to:c.to,text:c.text}),t)for(var f in c)(u=f.match(/^spans_(\d+)$/))&&R(t,Number(u[1]))>-1&&(G(l)[f]=c[f],delete c[f])}}}return r}function $i(e,t,n,r){if(r){var i=e.anchor;if(n){var o=tt(t,i)<0;o!=tt(n,i)<0?(i=t,t=n):o!=tt(t,n)<0&&(t=n)}return new Ci(i,t)}return new Ci(n||t,t)}function Gi(e,t,n,r,i){null==i&&(i=e.cm&&(e.cm.display.shift||e.extend)),Ji(e,new ki([$i(e.sel.primary(),t,n,i)],0),r)}function Xi(e,t,n){for(var r=[],i=e.cm&&(e.cm.display.shift||e.extend),o=0;o<e.sel.ranges.length;o++)r[o]=$i(e.sel.ranges[o],t[o],null,i);Ji(e,Si(e.cm,r,e.sel.primIndex),n)}function Zi(e,t,n,r){var i=e.sel.ranges.slice(0);i[t]=n,Ji(e,Si(e.cm,i,e.sel.primIndex),r)}function Yi(e,t,n,r){Ji(e,Ti(t,n),r)}function Qi(e,t,n){var r=e.history.done,i=G(r);i&&i.ranges?(r[r.length-1]=t,eo(e,t,n)):Ji(e,t,n)}function Ji(e,t,n){eo(e,t,n),Bi(e,e.sel,e.cm?e.cm.curOp.id:NaN,n)}function eo(e,t,n){(ve(e,"beforeSelectionChange")||e.cm&&ve(e.cm,"beforeSelectionChange"))&&(t=function(e,t,n){var r={ranges:t.ranges,update:function(t){this.ranges=[];for(var n=0;n<t.length;n++)this.ranges[n]=new Ci(lt(e,t[n].anchor),lt(e,t[n].head))},origin:n&&n.origin};return pe(e,"beforeSelectionChange",e,r),e.cm&&pe(e.cm,"beforeSelectionChange",e.cm,r),r.ranges!=t.ranges?Si(e.cm,r.ranges,r.ranges.length-1):t}(e,t,n));var r=n&&n.bias||(tt(t.primary().head,e.sel.primary().head)<0?-1:1);to(e,ro(e,t,r,!0)),n&&!1===n.scroll||!e.cm||Er(e.cm)}function to(e,t){t.equals(e.sel)||(e.sel=t,e.cm&&(e.cm.curOp.updateInput=1,e.cm.curOp.selectionChanged=!0,ge(e.cm)),sn(e,"cursorActivity",e))}function no(e){to(e,ro(e,e.sel,null,!1))}function ro(e,t,n,r){for(var i,o=0;o<t.ranges.length;o++){var a=t.ranges[o],l=t.ranges.length==e.sel.ranges.length&&e.sel.ranges[o],s=oo(e,a.anchor,l&&l.anchor,n,r),c=oo(e,a.head,l&&l.head,n,r);(i||s!=a.anchor||c!=a.head)&&(i||(i=t.ranges.slice(0,o)),i[o]=new Ci(s,c))}return i?Si(e.cm,i,t.primIndex):t}function io(e,t,n,r,i){var o=Ke(e,t.line);if(o.markedSpans)for(var a=0;a<o.markedSpans.length;++a){var l=o.markedSpans[a],s=l.marker,c="selectLeft"in s?!s.selectLeft:s.inclusiveLeft,u="selectRight"in s?!s.selectRight:s.inclusiveRight;if((null==l.from||(c?l.from<=t.ch:l.from<t.ch))&&(null==l.to||(u?l.to>=t.ch:l.to>t.ch))){if(i&&(pe(s,"beforeCursorEnter"),s.explicitlyCleared)){if(o.markedSpans){--a;continue}break}if(!s.atomic)continue;if(n){var f=s.find(r<0?1:-1),d=void 0;if((r<0?u:c)&&(f=ao(e,f,-r,f&&f.line==t.line?o:null)),f&&f.line==t.line&&(d=tt(f,n))&&(r<0?d<0:d>0))return io(e,f,t,r,i)}var h=s.find(r<0?-1:1);return(r<0?c:u)&&(h=ao(e,h,r,h.line==t.line?o:null)),h?io(e,h,t,r,i):null}}return t}function oo(e,t,n,r,i){var o=r||1,a=io(e,t,n,o,i)||!i&&io(e,t,n,o,!0)||io(e,t,n,-o,i)||!i&&io(e,t,n,-o,!0);return a||(e.cantEdit=!0,et(e.first,0))}function ao(e,t,n,r){return n<0&&0==t.ch?t.line>e.first?lt(e,et(t.line-1)):null:n>0&&t.ch==(r||Ke(e,t.line)).text.length?t.line<e.first+e.size-1?et(t.line+1,0):null:new et(t.line,t.ch+n)}function lo(e){e.setSelection(et(e.firstLine(),0),et(e.lastLine()),j)}function so(e,t,n){var r={canceled:!1,from:t.from,to:t.to,text:t.text,origin:t.origin,cancel:function(){return r.canceled=!0}};return n&&(r.update=function(t,n,i,o){t&&(r.from=lt(e,t)),n&&(r.to=lt(e,n)),i&&(r.text=i),void 0!==o&&(r.origin=o)}),pe(e,"beforeChange",e,r),e.cm&&pe(e.cm,"beforeChange",e.cm,r),r.canceled?(e.cm&&(e.cm.curOp.updateInput=2),null):{from:r.from,to:r.to,text:r.text,origin:r.origin}}function co(e,t,n){if(e.cm){if(!e.cm.curOp)return ei(e.cm,co)(e,t,n);if(e.cm.state.suppressEdits)return}if(!(ve(e,"beforeChange")||e.cm&&ve(e.cm,"beforeChange"))||(t=so(e,t,!0))){var r=wt&&!n&&function(e,t,n){var r=null;if(e.iter(t.line,n.line+1,(function(e){if(e.markedSpans)for(var t=0;t<e.markedSpans.length;++t){var n=e.markedSpans[t].marker;!n.readOnly||r&&-1!=R(r,n)||(r||(r=[])).push(n)}})),!r)return null;for(var i=[{from:t,to:n}],o=0;o<r.length;++o)for(var a=r[o],l=a.find(0),s=0;s<i.length;++s){var c=i[s];if(!(tt(c.to,l.from)<0||tt(c.from,l.to)>0)){var u=[s,1],f=tt(c.from,l.from),d=tt(c.to,l.to);(f<0||!a.inclusiveLeft&&!f)&&u.push({from:c.from,to:l.from}),(d>0||!a.inclusiveRight&&!d)&&u.push({from:l.to,to:c.to}),i.splice.apply(i,u),s+=u.length-3}}return i}(e,t.from,t.to);if(r)for(var i=r.length-1;i>=0;--i)uo(e,{from:r[i].from,to:r[i].to,text:i?[""]:t.text,origin:t.origin});else uo(e,t)}}function uo(e,t){if(1!=t.text.length||""!=t.text[0]||0!=tt(t.from,t.to)){var n=Oi(e,t);Ri(e,t,n,e.cm?e.cm.curOp.id:NaN),po(e,t,n,Lt(e,t));var r=[];Di(e,(function(e,n){n||-1!=R(r,e.history)||(yo(e.history,t),r.push(e.history)),po(e,t,null,Lt(e,t))}))}}function fo(e,t,n){var r=e.cm&&e.cm.state.suppressEdits;if(!r||n){for(var i,o=e.history,a=e.sel,l="undo"==t?o.done:o.undone,s="undo"==t?o.undone:o.done,c=0;c<l.length&&(i=l[c],n?!i.ranges||i.equals(e.sel):i.ranges);c++);if(c!=l.length){for(o.lastOrigin=o.lastSelOrigin=null;;){if(!(i=l.pop()).ranges){if(r)return void l.push(i);break}if(ji(i,s),n&&!i.equals(e.sel))return void Ji(e,i,{clearRedo:!1});a=i}var u=[];ji(a,s),s.push({changes:u,generation:o.generation}),o.generation=i.generation||++o.maxGeneration;for(var f=ve(e,"beforeChange")||e.cm&&ve(e.cm,"beforeChange"),d=function(n){var r=i.changes[n];if(r.origin=t,f&&!so(e,r,!1))return l.length=0,{};u.push(Wi(e,r));var o=n?Oi(e,r):G(l);po(e,r,o,Vi(e,r)),!n&&e.cm&&e.cm.scrollIntoView({from:r.from,to:Li(r)});var a=[];Di(e,(function(e,t){t||-1!=R(a,e.history)||(yo(e.history,r),a.push(e.history)),po(e,r,null,Vi(e,r))}))},h=i.changes.length-1;h>=0;--h){var p=d(h);if(p)return p.v}}}}function ho(e,t){if(0!=t&&(e.first+=t,e.sel=new ki(X(e.sel.ranges,(function(e){return new Ci(et(e.anchor.line+t,e.anchor.ch),et(e.head.line+t,e.head.ch))})),e.sel.primIndex),e.cm)){fr(e.cm,e.first,e.first-t,t);for(var n=e.cm.display,r=n.viewFrom;r<n.viewTo;r++)dr(e.cm,r,"gutter")}}function po(e,t,n,r){if(e.cm&&!e.cm.curOp)return ei(e.cm,po)(e,t,n,r);if(t.to.line<e.first)ho(e,t.text.length-1-(t.to.line-t.from.line));else if(!(t.from.line>e.lastLine())){if(t.from.line<e.first){var i=t.text.length-1-(e.first-t.from.line);ho(e,i),t={from:et(e.first,0),to:et(t.to.line+i,t.to.ch),text:[G(t.text)],origin:t.origin}}var o=e.lastLine();t.to.line>o&&(t={from:t.from,to:et(o,Ke(e,o).text.length),text:[t.text[0]],origin:t.origin}),t.removed=$e(e,t.from,t.to),n||(n=Oi(e,t)),e.cm?function(e,t,n){var r=e.doc,i=e.display,o=t.from,a=t.to,l=!1,s=o.line;e.options.lineWrapping||(s=Ze(Wt(Ke(r,o.line))),r.iter(s,a.line+1,(function(e){if(e==i.maxLine)return l=!0,!0}))),r.sel.contains(t.from,t.to)>-1&&ge(e),Pi(r,t,n,lr(e)),e.options.lineWrapping||(r.iter(s,o.line+t.text.length,(function(e){var t=Ut(e);t>i.maxLineLength&&(i.maxLine=e,i.maxLineLength=t,i.maxLineChanged=!0,l=!1)})),l&&(e.curOp.updateMaxLine=!0)),function(e,t){if(e.modeFrontier=Math.min(e.modeFrontier,t),!(e.highlightFrontier<t-10)){for(var n=e.first,r=t-1;r>n;r--){var i=Ke(e,r).stateAfter;if(i&&(!(i instanceof ct)||r+i.lookAhead<t)){n=r+1;break}}e.highlightFrontier=Math.min(e.highlightFrontier,n)}}(r,o.line),ri(e,400);var c=t.text.length-(a.line-o.line)-1;t.full?fr(e):o.line!=a.line||1!=t.text.length||zi(e.doc,t)?fr(e,o.line,a.line+1,c):dr(e,o.line,"text");var u=ve(e,"changes"),f=ve(e,"change");if(f||u){var d={from:o,to:a,text:t.text,removed:t.removed,origin:t.origin};f&&sn(e,"change",e,d),u&&(e.curOp.changeObjs||(e.curOp.changeObjs=[])).push(d)}e.display.selForContextMenu=null}(e.cm,t,r):Pi(e,t,r),eo(e,n,j),e.cantEdit&&oo(e,et(e.firstLine(),0))&&(e.cantEdit=!1)}}function mo(e,t,n,r,i){var o;r||(r=n),tt(r,n)<0&&(n=(o=[r,n])[0],r=o[1]),"string"==typeof t&&(t=e.splitLines(t)),co(e,{from:n,to:r,text:t,origin:i})}function go(e,t,n,r){n<e.line?e.line+=r:t<e.line&&(e.line=t,e.ch=0)}function vo(e,t,n,r){for(var i=0;i<e.length;++i){var o=e[i],a=!0;if(o.ranges){o.copied||((o=e[i]=o.deepCopy()).copied=!0);for(var l=0;l<o.ranges.length;l++)go(o.ranges[l].anchor,t,n,r),go(o.ranges[l].head,t,n,r)}else{for(var s=0;s<o.changes.length;++s){var c=o.changes[s];if(n<c.from.line)c.from=et(c.from.line+r,c.from.ch),c.to=et(c.to.line+r,c.to.ch);else if(t<=c.to.line){a=!1;break}}a||(e.splice(0,i+1),i=0)}}}function yo(e,t){var n=t.from.line,r=t.to.line,i=t.text.length-(r-n)-1;vo(e.done,n,r,i),vo(e.undone,n,r,i)}function bo(e,t,n,r){var i=t,o=t;return"number"==typeof t?o=Ke(e,at(e,t)):i=Ze(t),null==i?null:(r(o,i)&&e.cm&&dr(e.cm,i,n),o)}function xo(e){this.lines=e,this.parent=null;for(var t=0,n=0;n<e.length;++n)e[n].parent=this,t+=e[n].height;this.height=t}function wo(e){this.children=e;for(var t=0,n=0,r=0;r<e.length;++r){var i=e[r];t+=i.chunkSize(),n+=i.height,i.parent=this}this.size=t,this.height=n,this.parent=null}Ci.prototype.from=function(){return ot(this.anchor,this.head)},Ci.prototype.to=function(){return it(this.anchor,this.head)},Ci.prototype.empty=function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch},xo.prototype={chunkSize:function(){return this.lines.length},removeInner:function(e,t){for(var n=e,r=e+t;n<r;++n){var i=this.lines[n];this.height-=i.height,$t(i),sn(i,"delete")}this.lines.splice(e,t)},collapse:function(e){e.push.apply(e,this.lines)},insertInner:function(e,t,n){this.height+=n,this.lines=this.lines.slice(0,e).concat(t).concat(this.lines.slice(e));for(var r=0;r<t.length;++r)t[r].parent=this},iterN:function(e,t,n){for(var r=e+t;e<r;++e)if(n(this.lines[e]))return!0}},wo.prototype={chunkSize:function(){return this.size},removeInner:function(e,t){this.size-=t;for(var n=0;n<this.children.length;++n){var r=this.children[n],i=r.chunkSize();if(e<i){var o=Math.min(t,i-e),a=r.height;if(r.removeInner(e,o),this.height-=a-r.height,i==o&&(this.children.splice(n--,1),r.parent=null),0==(t-=o))break;e=0}else e-=i}if(this.size-t<25&&(this.children.length>1||!(this.children[0]instanceof xo))){var l=[];this.collapse(l),this.children=[new xo(l)],this.children[0].parent=this}},collapse:function(e){for(var t=0;t<this.children.length;++t)this.children[t].collapse(e)},insertInner:function(e,t,n){this.size+=t.length,this.height+=n;for(var r=0;r<this.children.length;++r){var i=this.children[r],o=i.chunkSize();if(e<=o){if(i.insertInner(e,t,n),i.lines&&i.lines.length>50){for(var a=i.lines.length%25+25,l=a;l<i.lines.length;){var s=new xo(i.lines.slice(l,l+=25));i.height-=s.height,this.children.splice(++r,0,s),s.parent=this}i.lines=i.lines.slice(0,a),this.maybeSpill()}break}e-=o}},maybeSpill:function(){if(!(this.children.length<=10)){var e=this;do{var t=new wo(e.children.splice(e.children.length-5,5));if(e.parent){e.size-=t.size,e.height-=t.height;var n=R(e.parent.children,e);e.parent.children.splice(n+1,0,t)}else{var r=new wo(e.children);r.parent=e,e.children=[r,t],e=r}t.parent=e.parent}while(e.children.length>10);e.parent.maybeSpill()}},iterN:function(e,t,n){for(var r=0;r<this.children.length;++r){var i=this.children[r],o=i.chunkSize();if(e<o){var a=Math.min(t,o-e);if(i.iterN(e,a,n))return!0;if(0==(t-=a))break;e=0}else e-=o}}};var ko=function(e,t,n){if(n)for(var r in n)n.hasOwnProperty(r)&&(this[r]=n[r]);this.doc=e,this.node=t};function Co(e,t,n){qt(t)<(e.curOp&&e.curOp.scrollTop||e.doc.scrollTop)&&Ar(e,n)}ko.prototype.clear=function(){var e=this.doc.cm,t=this.line.widgets,n=this.line,r=Ze(n);if(null!=r&&t){for(var i=0;i<t.length;++i)t[i]==this&&t.splice(i--,1);t.length||(n.widgets=null);var o=wn(this);Xe(n,Math.max(0,n.height-o)),e&&(Jr(e,(function(){Co(e,n,-o),dr(e,r,"widget")})),sn(e,"lineWidgetCleared",e,this,r))}},ko.prototype.changed=function(){var e=this,t=this.height,n=this.doc.cm,r=this.line;this.height=null;var i=wn(this)-t;i&&(Bt(this.doc,r)||Xe(r,r.height+i),n&&Jr(n,(function(){n.curOp.forceUpdate=!0,Co(n,r,i),sn(n,"lineWidgetChanged",n,e,Ze(r))})))},ye(ko);var So=0,To=function(e,t){this.lines=[],this.type=t,this.doc=e,this.id=++So};function Lo(e,t,n,r,i){if(r&&r.shared)return function(e,t,n,r,i){(r=_(r)).shared=!1;var o=[Lo(e,t,n,r,i)],a=o[0],l=r.widgetNode;return Di(e,(function(e){l&&(r.widgetNode=l.cloneNode(!0)),o.push(Lo(e,lt(e,t),lt(e,n),r,i));for(var s=0;s<e.linked.length;++s)if(e.linked[s].isParent)return;a=G(o)})),new Mo(o,a)}(e,t,n,r,i);if(e.cm&&!e.cm.curOp)return ei(e.cm,Lo)(e,t,n,r,i);var o=new To(e,i),a=tt(t,n);if(r&&_(r,o,!1),a>0||0==a&&!1!==o.clearWhenEmpty)return o;if(o.replacedWith&&(o.collapsed=!0,o.widgetNode=A("span",[o.replacedWith],"CodeMirror-widget"),r.handleMouseEvents||o.widgetNode.setAttribute("cm-ignore-events","true"),r.insertLeft&&(o.widgetNode.insertLeft=!0)),o.collapsed){if(_t(e,t.line,t,n,o)||t.line!=n.line&&_t(e,n.line,t,n,o))throw new Error("Inserting collapsed marker partially overlapping an existing one");kt=!0}o.addToHistory&&Ri(e,{from:t,to:n,origin:"markText"},e.sel,NaN);var l,s=t.line,c=e.cm;if(e.iter(s,n.line+1,(function(e){c&&o.collapsed&&!c.options.lineWrapping&&Wt(e)==c.display.maxLine&&(l=!0),o.collapsed&&s!=t.line&&Xe(e,0),function(e,t){e.markedSpans=e.markedSpans?e.markedSpans.concat([t]):[t],t.marker.attachLine(e)}(e,new Ct(o,s==t.line?t.ch:null,s==n.line?n.ch:null)),++s})),o.collapsed&&e.iter(t.line,n.line+1,(function(t){Bt(e,t)&&Xe(t,0)})),o.clearOnEnter&&fe(o,"beforeCursorEnter",(function(){return o.clear()})),o.readOnly&&(wt=!0,(e.history.done.length||e.history.undone.length)&&e.clearHistory()),o.collapsed&&(o.id=++So,o.atomic=!0),c){if(l&&(c.curOp.updateMaxLine=!0),o.collapsed)fr(c,t.line,n.line+1);else if(o.className||o.startStyle||o.endStyle||o.css||o.attributes||o.title)for(var u=t.line;u<=n.line;u++)dr(c,u,"text");o.atomic&&no(c.doc),sn(c,"markerAdded",c,o)}return o}To.prototype.clear=function(){if(!this.explicitlyCleared){var e=this.doc.cm,t=e&&!e.curOp;if(t&&Kr(e),ve(this,"clear")){var n=this.find();n&&sn(this,"clear",n.from,n.to)}for(var r=null,i=null,o=0;o<this.lines.length;++o){var a=this.lines[o],l=St(a.markedSpans,this);e&&!this.collapsed?dr(e,Ze(a),"text"):e&&(null!=l.to&&(i=Ze(a)),null!=l.from&&(r=Ze(a))),a.markedSpans=Tt(a.markedSpans,l),null==l.from&&this.collapsed&&!Bt(this.doc,a)&&e&&Xe(a,rr(e.display))}if(e&&this.collapsed&&!e.options.lineWrapping)for(var s=0;s<this.lines.length;++s){var c=Wt(this.lines[s]),u=Ut(c);u>e.display.maxLineLength&&(e.display.maxLine=c,e.display.maxLineLength=u,e.display.maxLineChanged=!0)}null!=r&&e&&this.collapsed&&fr(e,r,i+1),this.lines.length=0,this.explicitlyCleared=!0,this.atomic&&this.doc.cantEdit&&(this.doc.cantEdit=!1,e&&no(e.doc)),e&&sn(e,"markerCleared",e,this,r,i),t&&$r(e),this.parent&&this.parent.clear()}},To.prototype.find=function(e,t){var n,r;null==e&&"bookmark"==this.type&&(e=1);for(var i=0;i<this.lines.length;++i){var o=this.lines[i],a=St(o.markedSpans,this);if(null!=a.from&&(n=et(t?o:Ze(o),a.from),-1==e))return n;if(null!=a.to&&(r=et(t?o:Ze(o),a.to),1==e))return r}return n&&{from:n,to:r}},To.prototype.changed=function(){var e=this,t=this.find(-1,!0),n=this,r=this.doc.cm;t&&r&&Jr(r,(function(){var i=t.line,o=Ze(t.line),a=En(r,o);if(a&&(Wn(a),r.curOp.selectionChanged=r.curOp.forceUpdate=!0),r.curOp.updateMaxLine=!0,!Bt(n.doc,i)&&null!=n.height){var l=n.height;n.height=null;var s=wn(n)-l;s&&Xe(i,i.height+s)}sn(r,"markerChanged",r,e)}))},To.prototype.attachLine=function(e){if(!this.lines.length&&this.doc.cm){var t=this.doc.cm.curOp;t.maybeHiddenMarkers&&-1!=R(t.maybeHiddenMarkers,this)||(t.maybeUnhiddenMarkers||(t.maybeUnhiddenMarkers=[])).push(this)}this.lines.push(e)},To.prototype.detachLine=function(e){if(this.lines.splice(R(this.lines,e),1),!this.lines.length&&this.doc.cm){var t=this.doc.cm.curOp;(t.maybeHiddenMarkers||(t.maybeHiddenMarkers=[])).push(this)}},ye(To);var Mo=function(e,t){this.markers=e,this.primary=t;for(var n=0;n<e.length;++n)e[n].parent=this};function Oo(e){return e.findMarks(et(e.first,0),e.clipPos(et(e.lastLine())),(function(e){return e.parent}))}function No(e){for(var t=function(t){var n=e[t],r=[n.primary.doc];Di(n.primary.doc,(function(e){return r.push(e)}));for(var i=0;i<n.markers.length;i++){var o=n.markers[i];-1==R(r,o.doc)&&(o.parent=null,n.markers.splice(i--,1))}},n=0;n<e.length;n++)t(n)}Mo.prototype.clear=function(){if(!this.explicitlyCleared){this.explicitlyCleared=!0;for(var e=0;e<this.markers.length;++e)this.markers[e].clear();sn(this,"clear")}},Mo.prototype.find=function(e,t){return this.primary.find(e,t)},ye(Mo);var Ao=0,Eo=function(e,t,n,r,i){if(!(this instanceof Eo))return new Eo(e,t,n,r,i);null==n&&(n=0),wo.call(this,[new xo([new Kt("",null)])]),this.first=n,this.scrollTop=this.scrollLeft=0,this.cantEdit=!1,this.cleanGeneration=1,this.modeFrontier=this.highlightFrontier=n;var o=et(n,0);this.sel=Ti(o),this.history=new _i(null),this.id=++Ao,this.modeOption=t,this.lineSep=r,this.direction="rtl"==i?"rtl":"ltr",this.extend=!1,"string"==typeof e&&(e=this.splitLines(e)),Pi(this,{from:o,to:o,text:e}),Ji(this,Ti(o),j)};Eo.prototype=Y(wo.prototype,{constructor:Eo,iter:function(e,t,n){n?this.iterN(e-this.first,t-e,n):this.iterN(this.first,this.first+this.size,e)},insert:function(e,t){for(var n=0,r=0;r<t.length;++r)n+=t[r].height;this.insertInner(e-this.first,t,n)},remove:function(e,t){this.removeInner(e-this.first,t)},getValue:function(e){var t=Ge(this,this.first,this.first+this.size);return!1===e?t:t.join(e||this.lineSeparator())},setValue:ni((function(e){var t=et(this.first,0),n=this.first+this.size-1;co(this,{from:t,to:et(n,Ke(this,n).text.length),text:this.splitLines(e),origin:"setValue",full:!0},!0),this.cm&&zr(this.cm,0,0),Ji(this,Ti(t),j)})),replaceRange:function(e,t,n,r){mo(this,e,t=lt(this,t),n=n?lt(this,n):t,r)},getRange:function(e,t,n){var r=$e(this,lt(this,e),lt(this,t));return!1===n?r:r.join(n||this.lineSeparator())},getLine:function(e){var t=this.getLineHandle(e);return t&&t.text},getLineHandle:function(e){if(Qe(this,e))return Ke(this,e)},getLineNumber:function(e){return Ze(e)},getLineHandleVisualStart:function(e){return"number"==typeof e&&(e=Ke(this,e)),Wt(e)},lineCount:function(){return this.size},firstLine:function(){return this.first},lastLine:function(){return this.first+this.size-1},clipPos:function(e){return lt(this,e)},getCursor:function(e){var t=this.sel.primary();return null==e||"head"==e?t.head:"anchor"==e?t.anchor:"end"==e||"to"==e||!1===e?t.to():t.from()},listSelections:function(){return this.sel.ranges},somethingSelected:function(){return this.sel.somethingSelected()},setCursor:ni((function(e,t,n){Yi(this,lt(this,"number"==typeof e?et(e,t||0):e),null,n)})),setSelection:ni((function(e,t,n){Yi(this,lt(this,e),lt(this,t||e),n)})),extendSelection:ni((function(e,t,n){Gi(this,lt(this,e),t&&lt(this,t),n)})),extendSelections:ni((function(e,t){Xi(this,st(this,e),t)})),extendSelectionsBy:ni((function(e,t){Xi(this,st(this,X(this.sel.ranges,e)),t)})),setSelections:ni((function(e,t,n){if(e.length){for(var r=[],i=0;i<e.length;i++)r[i]=new Ci(lt(this,e[i].anchor),lt(this,e[i].head));null==t&&(t=Math.min(e.length-1,this.sel.primIndex)),Ji(this,Si(this.cm,r,t),n)}})),addSelection:ni((function(e,t,n){var r=this.sel.ranges.slice(0);r.push(new Ci(lt(this,e),lt(this,t||e))),Ji(this,Si(this.cm,r,r.length-1),n)})),getSelection:function(e){for(var t,n=this.sel.ranges,r=0;r<n.length;r++){var i=$e(this,n[r].from(),n[r].to());t=t?t.concat(i):i}return!1===e?t:t.join(e||this.lineSeparator())},getSelections:function(e){for(var t=[],n=this.sel.ranges,r=0;r<n.length;r++){var i=$e(this,n[r].from(),n[r].to());!1!==e&&(i=i.join(e||this.lineSeparator())),t[r]=i}return t},replaceSelection:function(e,t,n){for(var r=[],i=0;i<this.sel.ranges.length;i++)r[i]=e;this.replaceSelections(r,t,n||"+input")},replaceSelections:ni((function(e,t,n){for(var r=[],i=this.sel,o=0;o<i.ranges.length;o++){var a=i.ranges[o];r[o]={from:a.from(),to:a.to(),text:this.splitLines(e[o]),origin:n}}for(var l=t&&"end"!=t&&function(e,t,n){for(var r=[],i=et(e.first,0),o=i,a=0;a<t.length;a++){var l=t[a],s=Ni(l.from,i,o),c=Ni(Li(l),i,o);if(i=l.to,o=c,"around"==n){var u=e.sel.ranges[a],f=tt(u.head,u.anchor)<0;r[a]=new Ci(f?c:s,f?s:c)}else r[a]=new Ci(s,s)}return new ki(r,e.sel.primIndex)}(this,r,t),s=r.length-1;s>=0;s--)co(this,r[s]);l?Qi(this,l):this.cm&&Er(this.cm)})),undo:ni((function(){fo(this,"undo")})),redo:ni((function(){fo(this,"redo")})),undoSelection:ni((function(){fo(this,"undo",!0)})),redoSelection:ni((function(){fo(this,"redo",!0)})),setExtending:function(e){this.extend=e},getExtending:function(){return this.extend},historySize:function(){for(var e=this.history,t=0,n=0,r=0;r<e.done.length;r++)e.done[r].ranges||++t;for(var i=0;i<e.undone.length;i++)e.undone[i].ranges||++n;return{undo:t,redo:n}},clearHistory:function(){var e=this;this.history=new _i(this.history.maxGeneration),Di(this,(function(t){return t.history=e.history}),!0)},markClean:function(){this.cleanGeneration=this.changeGeneration(!0)},changeGeneration:function(e){return e&&(this.history.lastOp=this.history.lastSelOp=this.history.lastOrigin=null),this.history.generation},isClean:function(e){return this.history.generation==(e||this.cleanGeneration)},getHistory:function(){return{done:Ki(this.history.done),undone:Ki(this.history.undone)}},setHistory:function(e){var t=this.history=new _i(this.history.maxGeneration);t.done=Ki(e.done.slice(0),null,!0),t.undone=Ki(e.undone.slice(0),null,!0)},setGutterMarker:ni((function(e,t,n){return bo(this,e,"gutter",(function(e){var r=e.gutterMarkers||(e.gutterMarkers={});return r[t]=n,!n&&te(r)&&(e.gutterMarkers=null),!0}))})),clearGutter:ni((function(e){var t=this;this.iter((function(n){n.gutterMarkers&&n.gutterMarkers[e]&&bo(t,n,"gutter",(function(){return n.gutterMarkers[e]=null,te(n.gutterMarkers)&&(n.gutterMarkers=null),!0}))}))})),lineInfo:function(e){var t;if("number"==typeof e){if(!Qe(this,e))return null;if(t=e,!(e=Ke(this,e)))return null}else if(null==(t=Ze(e)))return null;return{line:t,handle:e,text:e.text,gutterMarkers:e.gutterMarkers,textClass:e.textClass,bgClass:e.bgClass,wrapClass:e.wrapClass,widgets:e.widgets}},addLineClass:ni((function(e,t,n){return bo(this,e,"gutter"==t?"gutter":"class",(function(e){var r="text"==t?"textClass":"background"==t?"bgClass":"gutter"==t?"gutterClass":"wrapClass";if(e[r]){if(S(n).test(e[r]))return!1;e[r]+=" "+n}else e[r]=n;return!0}))})),removeLineClass:ni((function(e,t,n){return bo(this,e,"gutter"==t?"gutter":"class",(function(e){var r="text"==t?"textClass":"background"==t?"bgClass":"gutter"==t?"gutterClass":"wrapClass",i=e[r];if(!i)return!1;if(null==n)e[r]=null;else{var o=i.match(S(n));if(!o)return!1;var a=o.index+o[0].length;e[r]=i.slice(0,o.index)+(o.index&&a!=i.length?" ":"")+i.slice(a)||null}return!0}))})),addLineWidget:ni((function(e,t,n){return function(e,t,n,r){var i=new ko(e,n,r),o=e.cm;return o&&i.noHScroll&&(o.display.alignWidgets=!0),bo(e,t,"widget",(function(t){var n=t.widgets||(t.widgets=[]);if(null==i.insertAt?n.push(i):n.splice(Math.min(n.length-1,Math.max(0,i.insertAt)),0,i),i.line=t,o&&!Bt(e,t)){var r=qt(t)<e.scrollTop;Xe(t,t.height+wn(i)),r&&Ar(o,i.height),o.curOp.forceUpdate=!0}return!0})),o&&sn(o,"lineWidgetAdded",o,i,"number"==typeof t?t:Ze(t)),i}(this,e,t,n)})),removeLineWidget:function(e){e.clear()},markText:function(e,t,n){return Lo(this,lt(this,e),lt(this,t),n,n&&n.type||"range")},setBookmark:function(e,t){var n={replacedWith:t&&(null==t.nodeType?t.widget:t),insertLeft:t&&t.insertLeft,clearWhenEmpty:!1,shared:t&&t.shared,handleMouseEvents:t&&t.handleMouseEvents};return Lo(this,e=lt(this,e),e,n,"bookmark")},findMarksAt:function(e){var t=[],n=Ke(this,(e=lt(this,e)).line).markedSpans;if(n)for(var r=0;r<n.length;++r){var i=n[r];(null==i.from||i.from<=e.ch)&&(null==i.to||i.to>=e.ch)&&t.push(i.marker.parent||i.marker)}return t},findMarks:function(e,t,n){e=lt(this,e),t=lt(this,t);var r=[],i=e.line;return this.iter(e.line,t.line+1,(function(o){var a=o.markedSpans;if(a)for(var l=0;l<a.length;l++){var s=a[l];null!=s.to&&i==e.line&&e.ch>=s.to||null==s.from&&i!=e.line||null!=s.from&&i==t.line&&s.from>=t.ch||n&&!n(s.marker)||r.push(s.marker.parent||s.marker)}++i})),r},getAllMarks:function(){var e=[];return this.iter((function(t){var n=t.markedSpans;if(n)for(var r=0;r<n.length;++r)null!=n[r].from&&e.push(n[r].marker)})),e},posFromIndex:function(e){var t,n=this.first,r=this.lineSeparator().length;return this.iter((function(i){var o=i.text.length+r;if(o>e)return t=e,!0;e-=o,++n})),lt(this,et(n,t))},indexFromPos:function(e){var t=(e=lt(this,e)).ch;if(e.line<this.first||e.ch<0)return 0;var n=this.lineSeparator().length;return this.iter(this.first,e.line,(function(e){t+=e.text.length+n})),t},copy:function(e){var t=new Eo(Ge(this,this.first,this.first+this.size),this.modeOption,this.first,this.lineSep,this.direction);return t.scrollTop=this.scrollTop,t.scrollLeft=this.scrollLeft,t.sel=this.sel,t.extend=!1,e&&(t.history.undoDepth=this.history.undoDepth,t.setHistory(this.getHistory())),t},linkedDoc:function(e){e||(e={});var t=this.first,n=this.first+this.size;null!=e.from&&e.from>t&&(t=e.from),null!=e.to&&e.to<n&&(n=e.to);var r=new Eo(Ge(this,t,n),e.mode||this.modeOption,t,this.lineSep,this.direction);return e.sharedHist&&(r.history=this.history),(this.linked||(this.linked=[])).push({doc:r,sharedHist:e.sharedHist}),r.linked=[{doc:this,isParent:!0,sharedHist:e.sharedHist}],function(e,t){for(var n=0;n<t.length;n++){var r=t[n],i=r.find(),o=e.clipPos(i.from),a=e.clipPos(i.to);if(tt(o,a)){var l=Lo(e,o,a,r.primary,r.primary.type);r.markers.push(l),l.parent=r}}}(r,Oo(this)),r},unlinkDoc:function(e){if(e instanceof Ma&&(e=e.doc),this.linked)for(var t=0;t<this.linked.length;++t)if(this.linked[t].doc==e){this.linked.splice(t,1),e.unlinkDoc(this),No(Oo(this));break}if(e.history==this.history){var n=[e.id];Di(e,(function(e){return n.push(e.id)}),!0),e.history=new _i(null),e.history.done=Ki(this.history.done,n),e.history.undone=Ki(this.history.undone,n)}},iterLinkedDocs:function(e){Di(this,e)},getMode:function(){return this.mode},getEditor:function(){return this.cm},splitLines:function(e){return this.lineSep?e.split(this.lineSep):Ee(e)},lineSeparator:function(){return this.lineSep||"\n"},setDirection:ni((function(e){var t;"rtl"!=e&&(e="ltr"),e!=this.direction&&(this.direction=e,this.iter((function(e){return e.order=null})),this.cm&&Jr(t=this.cm,(function(){Fi(t),fr(t)})))}))}),Eo.prototype.eachLine=Eo.prototype.iter;var zo=0;function Po(e){var t=this;if(Do(t),!me(t,e)&&!kn(t.display,e)){be(e),a&&(zo=+new Date);var n=cr(t,e,!0),r=e.dataTransfer.files;if(n&&!t.isReadOnly())if(r&&r.length&&window.FileReader&&window.File)for(var i=r.length,o=Array(i),l=0,s=function(){++l==i&&ei(t,(function(){var e={from:n=lt(t.doc,n),to:n,text:t.doc.splitLines(o.filter((function(e){return null!=e})).join(t.doc.lineSeparator())),origin:"paste"};co(t.doc,e),Qi(t.doc,Ti(lt(t.doc,n),lt(t.doc,Li(e))))}))()},c=function(e,n){if(t.options.allowDropFileTypes&&-1==R(t.options.allowDropFileTypes,e.type))s();else{var r=new FileReader;r.onerror=function(){return s()},r.onload=function(){var e=r.result;/[\x00-\x08\x0e-\x1f]{2}/.test(e)||(o[n]=e),s()},r.readAsText(e)}},u=0;u<r.length;u++)c(r[u],u);else{if(t.state.draggingText&&t.doc.sel.contains(n)>-1)return t.state.draggingText(e),void setTimeout((function(){return t.display.input.focus()}),20);try{var f=e.dataTransfer.getData("Text");if(f){var d;if(t.state.draggingText&&!t.state.draggingText.copy&&(d=t.listSelections()),eo(t.doc,Ti(n,n)),d)for(var h=0;h<d.length;++h)mo(t.doc,"",d[h].anchor,d[h].head,"drag");t.replaceSelection(f,"around","paste"),t.display.input.focus()}}catch(e){}}}}function Do(e){e.display.dragCursor&&(e.display.lineSpace.removeChild(e.display.dragCursor),e.display.dragCursor=null)}function Io(e){if(document.getElementsByClassName){for(var t=document.getElementsByClassName("CodeMirror"),n=[],r=0;r<t.length;r++){var i=t[r].CodeMirror;i&&n.push(i)}n.length&&n[0].operation((function(){for(var t=0;t<n.length;t++)e(n[t])}))}}var Fo=!1;function _o(){var e;Fo||(fe(window,"resize",(function(){null==e&&(e=setTimeout((function(){e=null,Io(Wo)}),100))})),fe(window,"blur",(function(){return Io(Tr)})),Fo=!0)}function Wo(e){var t=e.display;t.cachedCharWidth=t.cachedTextHeight=t.cachedPaddingH=null,t.scrollbarsClipped=!1,e.setSize()}for(var Ho={3:"Pause",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",106:"*",107:"=",109:"-",110:".",111:"/",145:"ScrollLock",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'",224:"Mod",63232:"Up",63233:"Down",63234:"Left",63235:"Right",63272:"Delete",63273:"Home",63275:"End",63276:"PageUp",63277:"PageDown",63302:"Insert"},Ro=0;Ro<10;Ro++)Ho[Ro+48]=Ho[Ro+96]=String(Ro);for(var Bo=65;Bo<=90;Bo++)Ho[Bo]=String.fromCharCode(Bo);for(var jo=1;jo<=12;jo++)Ho[jo+111]=Ho[jo+63235]="F"+jo;var qo={};function Uo(e){var t,n,r,i,o=e.split(/-(?!$)/);e=o[o.length-1];for(var a=0;a<o.length-1;a++){var l=o[a];if(/^(cmd|meta|m)$/i.test(l))i=!0;else if(/^a(lt)?$/i.test(l))t=!0;else if(/^(c|ctrl|control)$/i.test(l))n=!0;else{if(!/^s(hift)?$/i.test(l))throw new Error("Unrecognized modifier name: "+l);r=!0}}return t&&(e="Alt-"+e),n&&(e="Ctrl-"+e),i&&(e="Cmd-"+e),r&&(e="Shift-"+e),e}function Vo(e){var t={};for(var n in e)if(e.hasOwnProperty(n)){var r=e[n];if(/^(name|fallthrough|(de|at)tach)$/.test(n))continue;if("..."==r){delete e[n];continue}for(var i=X(n.split(" "),Uo),o=0;o<i.length;o++){var a=void 0,l=void 0;o==i.length-1?(l=i.join(" "),a=r):(l=i.slice(0,o+1).join(" "),a="...");var s=t[l];if(s){if(s!=a)throw new Error("Inconsistent bindings for "+l)}else t[l]=a}delete e[n]}for(var c in t)e[c]=t[c];return e}function Ko(e,t,n,r){var i=(t=Zo(t)).call?t.call(e,r):t[e];if(!1===i)return"nothing";if("..."===i)return"multi";if(null!=i&&n(i))return"handled";if(t.fallthrough){if("[object Array]"!=Object.prototype.toString.call(t.fallthrough))return Ko(e,t.fallthrough,n,r);for(var o=0;o<t.fallthrough.length;o++){var a=Ko(e,t.fallthrough[o],n,r);if(a)return a}}}function $o(e){var t="string"==typeof e?e:Ho[e.keyCode];return"Ctrl"==t||"Alt"==t||"Shift"==t||"Mod"==t}function Go(e,t,n){var r=e;return t.altKey&&"Alt"!=r&&(e="Alt-"+e),(k?t.metaKey:t.ctrlKey)&&"Ctrl"!=r&&(e="Ctrl-"+e),(k?t.ctrlKey:t.metaKey)&&"Mod"!=r&&(e="Cmd-"+e),!n&&t.shiftKey&&"Shift"!=r&&(e="Shift-"+e),e}function Xo(e,t){if(f&&34==e.keyCode&&e.char)return!1;var n=Ho[e.keyCode];return null!=n&&!e.altGraphKey&&(3==e.keyCode&&e.code&&(n=e.code),Go(n,e,t))}function Zo(e){return"string"==typeof e?qo[e]:e}function Yo(e,t){for(var n=e.doc.sel.ranges,r=[],i=0;i<n.length;i++){for(var o=t(n[i]);r.length&&tt(o.from,G(r).to)<=0;){var a=r.pop();if(tt(a.from,o.from)<0){o.from=a.from;break}}r.push(o)}Jr(e,(function(){for(var t=r.length-1;t>=0;t--)mo(e.doc,"",r[t].from,r[t].to,"+delete");Er(e)}))}function Qo(e,t,n){var r=ie(e.text,t+n,n);return r<0||r>e.text.length?null:r}function Jo(e,t,n){var r=Qo(e,t.ch,n);return null==r?null:new et(t.line,r,n<0?"after":"before")}function ea(e,t,n,r,i){if(e){"rtl"==t.doc.direction&&(i=-i);var o=ce(n,t.doc.direction);if(o){var a,l=i<0?G(o):o[0],s=i<0==(1==l.level)?"after":"before";if(l.level>0||"rtl"==t.doc.direction){var c=zn(t,n);a=i<0?n.text.length-1:0;var u=Pn(t,c,a).top;a=oe((function(e){return Pn(t,c,e).top==u}),i<0==(1==l.level)?l.from:l.to-1,a),"before"==s&&(a=Qo(n,a,1))}else a=i<0?l.to:l.from;return new et(r,a,s)}}return new et(r,i<0?n.text.length:0,i<0?"before":"after")}qo.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"},qo.pcDefault={"Ctrl-A":"selectAll","Ctrl-D":"deleteLine","Ctrl-Z":"undo","Shift-Ctrl-Z":"redo","Ctrl-Y":"redo","Ctrl-Home":"goDocStart","Ctrl-End":"goDocEnd","Ctrl-Up":"goLineUp","Ctrl-Down":"goLineDown","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"},qo.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","Ctrl-O":"openLine"},qo.macDefault={"Cmd-A":"selectAll","Cmd-D":"deleteLine","Cmd-Z":"undo","Shift-Cmd-Z":"redo","Cmd-Y":"redo","Cmd-Home":"goDocStart","Cmd-Up":"goDocStart","Cmd-End":"goDocEnd","Cmd-Down":"goDocEnd","Alt-Left":"goGroupLeft","Alt-Right":"goGroupRight","Cmd-Left":"goLineLeft","Cmd-Right":"goLineRight","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":"delWrappedLineLeft","Cmd-Delete":"delWrappedLineRight","Cmd-U":"undoSelection","Shift-Cmd-U":"redoSelection","Ctrl-Up":"goDocStart","Ctrl-Down":"goDocEnd",fallthrough:["basic","emacsy"]},qo.default=y?qo.macDefault:qo.pcDefault;var ta={selectAll:lo,singleSelection:function(e){return e.setSelection(e.getCursor("anchor"),e.getCursor("head"),j)},killLine:function(e){return Yo(e,(function(t){if(t.empty()){var n=Ke(e.doc,t.head.line).text.length;return t.head.ch==n&&t.head.line<e.lastLine()?{from:t.head,to:et(t.head.line+1,0)}:{from:t.head,to:et(t.head.line,n)}}return{from:t.from(),to:t.to()}}))},deleteLine:function(e){return Yo(e,(function(t){return{from:et(t.from().line,0),to:lt(e.doc,et(t.to().line+1,0))}}))},delLineLeft:function(e){return Yo(e,(function(e){return{from:et(e.from().line,0),to:e.from()}}))},delWrappedLineLeft:function(e){return Yo(e,(function(t){var n=e.charCoords(t.head,"div").top+5;return{from:e.coordsChar({left:0,top:n},"div"),to:t.from()}}))},delWrappedLineRight:function(e){return Yo(e,(function(t){var n=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:e.display.lineDiv.offsetWidth+100,top:n},"div");return{from:t.from(),to:r}}))},undo:function(e){return e.undo()},redo:function(e){return e.redo()},undoSelection:function(e){return e.undoSelection()},redoSelection:function(e){return e.redoSelection()},goDocStart:function(e){return e.extendSelection(et(e.firstLine(),0))},goDocEnd:function(e){return e.extendSelection(et(e.lastLine()))},goLineStart:function(e){return e.extendSelectionsBy((function(t){return na(e,t.head.line)}),{origin:"+move",bias:1})},goLineStartSmart:function(e){return e.extendSelectionsBy((function(t){return ra(e,t.head)}),{origin:"+move",bias:1})},goLineEnd:function(e){return e.extendSelectionsBy((function(t){return function(e,t){var n=Ke(e.doc,t),r=function(e){for(var t;t=It(e);)e=t.find(1,!0).line;return e}(n);return r!=n&&(t=Ze(r)),ea(!0,e,n,t,-1)}(e,t.head.line)}),{origin:"+move",bias:-1})},goLineRight:function(e){return e.extendSelectionsBy((function(t){var n=e.cursorCoords(t.head,"div").top+5;return e.coordsChar({left:e.display.lineDiv.offsetWidth+100,top:n},"div")}),U)},goLineLeft:function(e){return e.extendSelectionsBy((function(t){var n=e.cursorCoords(t.head,"div").top+5;return e.coordsChar({left:0,top:n},"div")}),U)},goLineLeftSmart:function(e){return e.extendSelectionsBy((function(t){var n=e.cursorCoords(t.head,"div").top+5,r=e.coordsChar({left:0,top:n},"div");return r.ch<e.getLine(r.line).search(/\S/)?ra(e,t.head):r}),U)},goLineUp:function(e){return e.moveV(-1,"line")},goLineDown:function(e){return e.moveV(1,"line")},goPageUp:function(e){return e.moveV(-1,"page")},goPageDown:function(e){return e.moveV(1,"page")},goCharLeft:function(e){return e.moveH(-1,"char")},goCharRight:function(e){return e.moveH(1,"char")},goColumnLeft:function(e){return e.moveH(-1,"column")},goColumnRight:function(e){return e.moveH(1,"column")},goWordLeft:function(e){return e.moveH(-1,"word")},goGroupRight:function(e){return e.moveH(1,"group")},goGroupLeft:function(e){return e.moveH(-1,"group")},goWordRight:function(e){return e.moveH(1,"word")},delCharBefore:function(e){return e.deleteH(-1,"codepoint")},delCharAfter:function(e){return e.deleteH(1,"char")},delWordBefore:function(e){return e.deleteH(-1,"word")},delWordAfter:function(e){return e.deleteH(1,"word")},delGroupBefore:function(e){return e.deleteH(-1,"group")},delGroupAfter:function(e){return e.deleteH(1,"group")},indentAuto:function(e){return e.indentSelection("smart")},indentMore:function(e){return e.indentSelection("add")},indentLess:function(e){return e.indentSelection("subtract")},insertTab:function(e){return e.replaceSelection("\t")},insertSoftTab:function(e){for(var t=[],n=e.listSelections(),r=e.options.tabSize,i=0;i<n.length;i++){var o=n[i].from(),a=W(e.getLine(o.line),o.ch,r);t.push($(r-a%r))}e.replaceSelections(t)},defaultTab:function(e){e.somethingSelected()?e.indentSelection("add"):e.execCommand("insertTab")},transposeChars:function(e){return Jr(e,(function(){for(var t=e.listSelections(),n=[],r=0;r<t.length;r++)if(t[r].empty()){var i=t[r].head,o=Ke(e.doc,i.line).text;if(o)if(i.ch==o.length&&(i=new et(i.line,i.ch-1)),i.ch>0)i=new et(i.line,i.ch+1),e.replaceRange(o.charAt(i.ch-1)+o.charAt(i.ch-2),et(i.line,i.ch-2),i,"+transpose");else if(i.line>e.doc.first){var a=Ke(e.doc,i.line-1).text;a&&(i=new et(i.line,1),e.replaceRange(o.charAt(0)+e.doc.lineSeparator()+a.charAt(a.length-1),et(i.line-1,a.length-1),i,"+transpose"))}n.push(new Ci(i,i))}e.setSelections(n)}))},newlineAndIndent:function(e){return Jr(e,(function(){for(var t=e.listSelections(),n=t.length-1;n>=0;n--)e.replaceRange(e.doc.lineSeparator(),t[n].anchor,t[n].head,"+input");t=e.listSelections();for(var r=0;r<t.length;r++)e.indentLine(t[r].from().line,null,!0);Er(e)}))},openLine:function(e){return e.replaceSelection("\n","start")},toggleOverwrite:function(e){return e.toggleOverwrite()}};function na(e,t){var n=Ke(e.doc,t),r=Wt(n);return r!=n&&(t=Ze(r)),ea(!0,e,r,t,1)}function ra(e,t){var n=na(e,t.line),r=Ke(e.doc,n.line),i=ce(r,e.doc.direction);if(!i||0==i[0].level){var o=Math.max(n.ch,r.text.search(/\S/)),a=t.line==n.line&&t.ch<=o&&t.ch;return et(n.line,a?0:o,n.sticky)}return n}function ia(e,t,n){if("string"==typeof t&&!(t=ta[t]))return!1;e.display.input.ensurePolled();var r=e.display.shift,i=!1;try{e.isReadOnly()&&(e.state.suppressEdits=!0),n&&(e.display.shift=!1),i=t(e)!=B}finally{e.display.shift=r,e.state.suppressEdits=!1}return i}var oa=new H;function aa(e,t,n,r){var i=e.state.keySeq;if(i){if($o(t))return"handled";if(/\'$/.test(t)?e.state.keySeq=null:oa.set(50,(function(){e.state.keySeq==i&&(e.state.keySeq=null,e.display.input.reset())})),la(e,i+" "+t,n,r))return!0}return la(e,t,n,r)}function la(e,t,n,r){var i=function(e,t,n){for(var r=0;r<e.state.keyMaps.length;r++){var i=Ko(t,e.state.keyMaps[r],n,e);if(i)return i}return e.options.extraKeys&&Ko(t,e.options.extraKeys,n,e)||Ko(t,e.options.keyMap,n,e)}(e,t,r);return"multi"==i&&(e.state.keySeq=t),"handled"==i&&sn(e,"keyHandled",e,t,n),"handled"!=i&&"multi"!=i||(be(n),wr(e)),!!i}function sa(e,t){var n=Xo(t,!0);return!!n&&(t.shiftKey&&!e.state.keySeq?aa(e,"Shift-"+n,t,(function(t){return ia(e,t,!0)}))||aa(e,n,t,(function(t){if("string"==typeof t?/^go[A-Z]/.test(t):t.motion)return ia(e,t)})):aa(e,n,t,(function(t){return ia(e,t)})))}var ca=null;function ua(e){var t=this;if(!(e.target&&e.target!=t.display.input.getField()||(t.curOp.focus=z(),me(t,e)))){a&&l<11&&27==e.keyCode&&(e.returnValue=!1);var r=e.keyCode;t.display.shift=16==r||e.shiftKey;var i=sa(t,e);f&&(ca=i?r:null,i||88!=r||Pe||!(y?e.metaKey:e.ctrlKey)||t.replaceSelection("",null,"cut")),n&&!y&&!i&&46==r&&e.shiftKey&&!e.ctrlKey&&document.execCommand&&document.execCommand("cut"),18!=r||/\bCodeMirror-crosshair\b/.test(t.display.lineDiv.className)||function(e){var t=e.display.lineDiv;function n(e){18!=e.keyCode&&e.altKey||(L(t,"CodeMirror-crosshair"),he(document,"keyup",n),he(document,"mouseover",n))}P(t,"CodeMirror-crosshair"),fe(document,"keyup",n),fe(document,"mouseover",n)}(t)}}function fa(e){16==e.keyCode&&(this.doc.sel.shift=!1),me(this,e)}function da(e){var t=this;if(!(e.target&&e.target!=t.display.input.getField()||kn(t.display,e)||me(t,e)||e.ctrlKey&&!e.altKey||y&&e.metaKey)){var n=e.keyCode,r=e.charCode;if(f&&n==ca)return ca=null,void be(e);if(!f||e.which&&!(e.which<10)||!sa(t,e)){var i=String.fromCharCode(null==r?n:r);"\b"!=i&&(function(e,t,n){return aa(e,"'"+n+"'",t,(function(t){return ia(e,t,!0)}))}(t,e,i)||t.display.input.onKeyPress(e))}}}var ha,pa,ma=function(e,t,n){this.time=e,this.pos=t,this.button=n};function ga(e){var t=this,n=t.display;if(!(me(t,e)||n.activeTouch&&n.input.supportsTouch()))if(n.input.ensurePolled(),n.shift=e.shiftKey,kn(n,e))s||(n.scroller.draggable=!1,setTimeout((function(){return n.scroller.draggable=!0}),100));else if(!ba(t,e)){var r=cr(t,e),i=Se(e),o=r?function(e,t){var n=+new Date;return pa&&pa.compare(n,e,t)?(ha=pa=null,"triple"):ha&&ha.compare(n,e,t)?(pa=new ma(n,e,t),ha=null,"double"):(ha=new ma(n,e,t),pa=null,"single")}(r,i):"single";window.focus(),1==i&&t.state.selectingText&&t.state.selectingText(e),r&&function(e,t,n,r,i){var o="Click";return"double"==r?o="Double"+o:"triple"==r&&(o="Triple"+o),aa(e,Go(o=(1==t?"Left":2==t?"Middle":"Right")+o,i),i,(function(t){if("string"==typeof t&&(t=ta[t]),!t)return!1;var r=!1;try{e.isReadOnly()&&(e.state.suppressEdits=!0),r=t(e,n)!=B}finally{e.state.suppressEdits=!1}return r}))}(t,i,r,o,e)||(1==i?r?function(e,t,n,r){a?setTimeout(F(kr,e),0):e.curOp.focus=z();var i,o=function(e,t,n){var r=e.getOption("configureMouse"),i=r?r(e,t,n):{};if(null==i.unit){var o=b?n.shiftKey&&n.metaKey:n.altKey;i.unit=o?"rectangle":"single"==t?"char":"double"==t?"word":"line"}return(null==i.extend||e.doc.extend)&&(i.extend=e.doc.extend||n.shiftKey),null==i.addNew&&(i.addNew=y?n.metaKey:n.ctrlKey),null==i.moveOnDrag&&(i.moveOnDrag=!(y?n.altKey:n.ctrlKey)),i}(e,n,r),c=e.doc.sel;e.options.dragDrop&&Me&&!e.isReadOnly()&&"single"==n&&(i=c.contains(t))>-1&&(tt((i=c.ranges[i]).from(),t)<0||t.xRel>0)&&(tt(i.to(),t)>0||t.xRel<0)?function(e,t,n,r){var i=e.display,o=!1,c=ei(e,(function(t){s&&(i.scroller.draggable=!1),e.state.draggingText=!1,he(i.wrapper.ownerDocument,"mouseup",c),he(i.wrapper.ownerDocument,"mousemove",u),he(i.scroller,"dragstart",f),he(i.scroller,"drop",c),o||(be(t),r.addNew||Gi(e.doc,n,null,null,r.extend),s&&!d||a&&9==l?setTimeout((function(){i.wrapper.ownerDocument.body.focus({preventScroll:!0}),i.input.focus()}),20):i.input.focus())})),u=function(e){o=o||Math.abs(t.clientX-e.clientX)+Math.abs(t.clientY-e.clientY)>=10},f=function(){return o=!0};s&&(i.scroller.draggable=!0),e.state.draggingText=c,c.copy=!r.moveOnDrag,i.scroller.dragDrop&&i.scroller.dragDrop(),fe(i.wrapper.ownerDocument,"mouseup",c),fe(i.wrapper.ownerDocument,"mousemove",u),fe(i.scroller,"dragstart",f),fe(i.scroller,"drop",c),Cr(e),setTimeout((function(){return i.input.focus()}),20)}(e,r,t,o):function(e,t,n,r){var i=e.display,o=e.doc;be(t);var a,l,s=o.sel,c=s.ranges;if(r.addNew&&!r.extend?(l=o.sel.contains(n),a=l>-1?c[l]:new Ci(n,n)):(a=o.sel.primary(),l=o.sel.primIndex),"rectangle"==r.unit)r.addNew||(a=new Ci(n,n)),n=cr(e,t,!0,!0),l=-1;else{var u=va(e,n,r.unit);a=r.extend?$i(a,u.anchor,u.head,r.extend):u}r.addNew?-1==l?(l=c.length,Ji(o,Si(e,c.concat([a]),l),{scroll:!1,origin:"*mouse"})):c.length>1&&c[l].empty()&&"char"==r.unit&&!r.extend?(Ji(o,Si(e,c.slice(0,l).concat(c.slice(l+1)),0),{scroll:!1,origin:"*mouse"}),s=o.sel):Zi(o,l,a,q):(l=0,Ji(o,new ki([a],0),q),s=o.sel);var f=n;function d(t){if(0!=tt(f,t))if(f=t,"rectangle"==r.unit){for(var i=[],c=e.options.tabSize,u=W(Ke(o,n.line).text,n.ch,c),d=W(Ke(o,t.line).text,t.ch,c),h=Math.min(u,d),p=Math.max(u,d),m=Math.min(n.line,t.line),g=Math.min(e.lastLine(),Math.max(n.line,t.line));m<=g;m++){var v=Ke(o,m).text,y=V(v,h,c);h==p?i.push(new Ci(et(m,y),et(m,y))):v.length>y&&i.push(new Ci(et(m,y),et(m,V(v,p,c))))}i.length||i.push(new Ci(n,n)),Ji(o,Si(e,s.ranges.slice(0,l).concat(i),l),{origin:"*mouse",scroll:!1}),e.scrollIntoView(t)}else{var b,x=a,w=va(e,t,r.unit),k=x.anchor;tt(w.anchor,k)>0?(b=w.head,k=ot(x.from(),w.anchor)):(b=w.anchor,k=it(x.to(),w.head));var C=s.ranges.slice(0);C[l]=function(e,t){var n=t.anchor,r=t.head,i=Ke(e.doc,n.line);if(0==tt(n,r)&&n.sticky==r.sticky)return t;var o=ce(i);if(!o)return t;var a=le(o,n.ch,n.sticky),l=o[a];if(l.from!=n.ch&&l.to!=n.ch)return t;var s,c=a+(l.from==n.ch==(1!=l.level)?0:1);if(0==c||c==o.length)return t;if(r.line!=n.line)s=(r.line-n.line)*("ltr"==e.doc.direction?1:-1)>0;else{var u=le(o,r.ch,r.sticky),f=u-a||(r.ch-n.ch)*(1==l.level?-1:1);s=u==c-1||u==c?f<0:f>0}var d=o[c+(s?-1:0)],h=s==(1==d.level),p=h?d.from:d.to,m=h?"after":"before";return n.ch==p&&n.sticky==m?t:new Ci(new et(n.line,p,m),r)}(e,new Ci(lt(o,k),b)),Ji(o,Si(e,C,l),q)}}var h=i.wrapper.getBoundingClientRect(),p=0;function m(t){e.state.selectingText=!1,p=1/0,t&&(be(t),i.input.focus()),he(i.wrapper.ownerDocument,"mousemove",g),he(i.wrapper.ownerDocument,"mouseup",v),o.history.lastSelOrigin=null}var g=ei(e,(function(t){0!==t.buttons&&Se(t)?function t(n){var a=++p,l=cr(e,n,!0,"rectangle"==r.unit);if(l)if(0!=tt(l,f)){e.curOp.focus=z(),d(l);var s=Or(i,o);(l.line>=s.to||l.line<s.from)&&setTimeout(ei(e,(function(){p==a&&t(n)})),150)}else{var c=n.clientY<h.top?-20:n.clientY>h.bottom?20:0;c&&setTimeout(ei(e,(function(){p==a&&(i.scroller.scrollTop+=c,t(n))})),50)}}(t):m(t)})),v=ei(e,m);e.state.selectingText=v,fe(i.wrapper.ownerDocument,"mousemove",g),fe(i.wrapper.ownerDocument,"mouseup",v)}(e,r,t,o)}(t,r,o,e):Ce(e)==n.scroller&&be(e):2==i?(r&&Gi(t.doc,r),setTimeout((function(){return n.input.focus()}),20)):3==i&&(C?t.display.input.onContextMenu(e):Cr(t)))}}function va(e,t,n){if("char"==n)return new Ci(t,t);if("word"==n)return e.findWordAt(t);if("line"==n)return new Ci(et(t.line,0),lt(e.doc,et(t.line+1,0)));var r=n(e,t);return new Ci(r.from,r.to)}function ya(e,t,n,r){var i,o;if(t.touches)i=t.touches[0].clientX,o=t.touches[0].clientY;else try{i=t.clientX,o=t.clientY}catch(e){return!1}if(i>=Math.floor(e.display.gutters.getBoundingClientRect().right))return!1;r&&be(t);var a=e.display,l=a.lineDiv.getBoundingClientRect();if(o>l.bottom||!ve(e,n))return we(t);o-=l.top-a.viewOffset;for(var s=0;s<e.display.gutterSpecs.length;++s){var c=a.gutters.childNodes[s];if(c&&c.getBoundingClientRect().right>=i)return pe(e,n,e,Ye(e.doc,o),e.display.gutterSpecs[s].className,t),we(t)}}function ba(e,t){return ya(e,t,"gutterClick",!0)}function xa(e,t){kn(e.display,t)||function(e,t){return!!ve(e,"gutterContextMenu")&&ya(e,t,"gutterContextMenu",!1)}(e,t)||me(e,t,"contextmenu")||C||e.display.input.onContextMenu(t)}function wa(e){e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+e.options.theme.replace(/(^|\s)\s*/g," cm-s-"),Rn(e)}ma.prototype.compare=function(e,t,n){return this.time+400>e&&0==tt(t,this.pos)&&n==this.button};var ka={toString:function(){return"CodeMirror.Init"}},Ca={},Sa={};function Ta(e,t,n){if(!t!=!(n&&n!=ka)){var r=e.display.dragFunctions,i=t?fe:he;i(e.display.scroller,"dragstart",r.start),i(e.display.scroller,"dragenter",r.enter),i(e.display.scroller,"dragover",r.over),i(e.display.scroller,"dragleave",r.leave),i(e.display.scroller,"drop",r.drop)}}function La(e){e.options.lineWrapping?(P(e.display.wrapper,"CodeMirror-wrap"),e.display.sizer.style.minWidth="",e.display.sizerWidth=null):(L(e.display.wrapper,"CodeMirror-wrap"),Vt(e)),sr(e),fr(e),Rn(e),setTimeout((function(){return Br(e)}),100)}function Ma(e,t){var n=this;if(!(this instanceof Ma))return new Ma(e,t);this.options=t=t?_(t):{},_(Ca,t,!1);var r=t.value;"string"==typeof r?r=new Eo(r,t.mode,null,t.lineSeparator,t.direction):t.mode&&(r.modeOption=t.mode),this.doc=r;var i=new Ma.inputStyles[t.inputStyle](this),o=this.display=new gi(e,r,i,t);for(var c in o.wrapper.CodeMirror=this,wa(this),t.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap"),Ur(this),this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,delayingBlurEvent:!1,focused:!1,suppressEdits:!1,pasteIncoming:-1,cutIncoming:-1,selectingText:!1,draggingText:!1,highlight:new H,keySeq:null,specialChars:null},t.autofocus&&!v&&o.input.focus(),a&&l<11&&setTimeout((function(){return n.display.input.reset(!0)}),20),function(e){var t=e.display;fe(t.scroller,"mousedown",ei(e,ga)),fe(t.scroller,"dblclick",a&&l<11?ei(e,(function(t){if(!me(e,t)){var n=cr(e,t);if(n&&!ba(e,t)&&!kn(e.display,t)){be(t);var r=e.findWordAt(n);Gi(e.doc,r.anchor,r.head)}}})):function(t){return me(e,t)||be(t)}),fe(t.scroller,"contextmenu",(function(t){return xa(e,t)})),fe(t.input.getField(),"contextmenu",(function(n){t.scroller.contains(n.target)||xa(e,n)}));var n,r={end:0};function i(){t.activeTouch&&(n=setTimeout((function(){return t.activeTouch=null}),1e3),(r=t.activeTouch).end=+new Date)}function o(e,t){if(null==t.left)return!0;var n=t.left-e.left,r=t.top-e.top;return n*n+r*r>400}fe(t.scroller,"touchstart",(function(i){if(!me(e,i)&&!function(e){if(1!=e.touches.length)return!1;var t=e.touches[0];return t.radiusX<=1&&t.radiusY<=1}(i)&&!ba(e,i)){t.input.ensurePolled(),clearTimeout(n);var o=+new Date;t.activeTouch={start:o,moved:!1,prev:o-r.end<=300?r:null},1==i.touches.length&&(t.activeTouch.left=i.touches[0].pageX,t.activeTouch.top=i.touches[0].pageY)}})),fe(t.scroller,"touchmove",(function(){t.activeTouch&&(t.activeTouch.moved=!0)})),fe(t.scroller,"touchend",(function(n){var r=t.activeTouch;if(r&&!kn(t,n)&&null!=r.left&&!r.moved&&new Date-r.start<300){var a,l=e.coordsChar(t.activeTouch,"page");a=!r.prev||o(r,r.prev)?new Ci(l,l):!r.prev.prev||o(r,r.prev.prev)?e.findWordAt(l):new Ci(et(l.line,0),lt(e.doc,et(l.line+1,0))),e.setSelection(a.anchor,a.head),e.focus(),be(n)}i()})),fe(t.scroller,"touchcancel",i),fe(t.scroller,"scroll",(function(){t.scroller.clientHeight&&(Ir(e,t.scroller.scrollTop),_r(e,t.scroller.scrollLeft,!0),pe(e,"scroll",e))})),fe(t.scroller,"mousewheel",(function(t){return wi(e,t)})),fe(t.scroller,"DOMMouseScroll",(function(t){return wi(e,t)})),fe(t.wrapper,"scroll",(function(){return t.wrapper.scrollTop=t.wrapper.scrollLeft=0})),t.dragFunctions={enter:function(t){me(e,t)||ke(t)},over:function(t){me(e,t)||(function(e,t){var n=cr(e,t);if(n){var r=document.createDocumentFragment();yr(e,n,r),e.display.dragCursor||(e.display.dragCursor=N("div",null,"CodeMirror-cursors CodeMirror-dragcursors"),e.display.lineSpace.insertBefore(e.display.dragCursor,e.display.cursorDiv)),O(e.display.dragCursor,r)}}(e,t),ke(t))},start:function(t){return function(e,t){if(a&&(!e.state.draggingText||+new Date-zo<100))ke(t);else if(!me(e,t)&&!kn(e.display,t)&&(t.dataTransfer.setData("Text",e.getSelection()),t.dataTransfer.effectAllowed="copyMove",t.dataTransfer.setDragImage&&!d)){var n=N("img",null,null,"position: fixed; left: 0; top: 0;");n.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",f&&(n.width=n.height=1,e.display.wrapper.appendChild(n),n._top=n.offsetTop),t.dataTransfer.setDragImage(n,0,0),f&&n.parentNode.removeChild(n)}}(e,t)},drop:ei(e,Po),leave:function(t){me(e,t)||Do(e)}};var s=t.input.getField();fe(s,"keyup",(function(t){return fa.call(e,t)})),fe(s,"keydown",ei(e,ua)),fe(s,"keypress",ei(e,da)),fe(s,"focus",(function(t){return Sr(e,t)})),fe(s,"blur",(function(t){return Tr(e,t)}))}(this),_o(),Kr(this),this.curOp.forceUpdate=!0,Ii(this,r),t.autofocus&&!v||this.hasFocus()?setTimeout((function(){n.hasFocus()&&!n.state.focused&&Sr(n)}),20):Tr(this),Sa)Sa.hasOwnProperty(c)&&Sa[c](this,t[c],ka);di(this),t.finishInit&&t.finishInit(this);for(var u=0;u<Oa.length;++u)Oa[u](this);$r(this),s&&t.lineWrapping&&"optimizelegibility"==getComputedStyle(o.lineDiv).textRendering&&(o.lineDiv.style.textRendering="auto")}Ma.defaults=Ca,Ma.optionHandlers=Sa;var Oa=[];function Na(e,t,n,r){var i,o=e.doc;null==n&&(n="add"),"smart"==n&&(o.mode.indent?i=ht(e,t).state:n="prev");var a=e.options.tabSize,l=Ke(o,t),s=W(l.text,null,a);l.stateAfter&&(l.stateAfter=null);var c,u=l.text.match(/^\s*/)[0];if(r||/\S/.test(l.text)){if("smart"==n&&((c=o.mode.indent(i,l.text.slice(u.length),l.text))==B||c>150)){if(!r)return;n="prev"}}else c=0,n="not";"prev"==n?c=t>o.first?W(Ke(o,t-1).text,null,a):0:"add"==n?c=s+e.options.indentUnit:"subtract"==n?c=s-e.options.indentUnit:"number"==typeof n&&(c=s+n),c=Math.max(0,c);var f="",d=0;if(e.options.indentWithTabs)for(var h=Math.floor(c/a);h;--h)d+=a,f+="\t";if(d<c&&(f+=$(c-d)),f!=u)return mo(o,f,et(t,0),et(t,u.length),"+input"),l.stateAfter=null,!0;for(var p=0;p<o.sel.ranges.length;p++){var m=o.sel.ranges[p];if(m.head.line==t&&m.head.ch<u.length){var g=et(t,u.length);Zi(o,p,new Ci(g,g));break}}}Ma.defineInitHook=function(e){return Oa.push(e)};var Aa=null;function Ea(e){Aa=e}function za(e,t,n,r,i){var o=e.doc;e.display.shift=!1,r||(r=o.sel);var a=+new Date-200,l="paste"==i||e.state.pasteIncoming>a,s=Ee(t),c=null;if(l&&r.ranges.length>1)if(Aa&&Aa.text.join("\n")==t){if(r.ranges.length%Aa.text.length==0){c=[];for(var u=0;u<Aa.text.length;u++)c.push(o.splitLines(Aa.text[u]))}}else s.length==r.ranges.length&&e.options.pasteLinesPerSelection&&(c=X(s,(function(e){return[e]})));for(var f=e.curOp.updateInput,d=r.ranges.length-1;d>=0;d--){var h=r.ranges[d],p=h.from(),m=h.to();h.empty()&&(n&&n>0?p=et(p.line,p.ch-n):e.state.overwrite&&!l?m=et(m.line,Math.min(Ke(o,m.line).text.length,m.ch+G(s).length)):l&&Aa&&Aa.lineWise&&Aa.text.join("\n")==s.join("\n")&&(p=m=et(p.line,0)));var g={from:p,to:m,text:c?c[d%c.length]:s,origin:i||(l?"paste":e.state.cutIncoming>a?"cut":"+input")};co(e.doc,g),sn(e,"inputRead",e,g)}t&&!l&&Da(e,t),Er(e),e.curOp.updateInput<2&&(e.curOp.updateInput=f),e.curOp.typing=!0,e.state.pasteIncoming=e.state.cutIncoming=-1}function Pa(e,t){var n=e.clipboardData&&e.clipboardData.getData("Text");if(n)return e.preventDefault(),t.isReadOnly()||t.options.disableInput||Jr(t,(function(){return za(t,n,0,null,"paste")})),!0}function Da(e,t){if(e.options.electricChars&&e.options.smartIndent)for(var n=e.doc.sel,r=n.ranges.length-1;r>=0;r--){var i=n.ranges[r];if(!(i.head.ch>100||r&&n.ranges[r-1].head.line==i.head.line)){var o=e.getModeAt(i.head),a=!1;if(o.electricChars){for(var l=0;l<o.electricChars.length;l++)if(t.indexOf(o.electricChars.charAt(l))>-1){a=Na(e,i.head.line,"smart");break}}else o.electricInput&&o.electricInput.test(Ke(e.doc,i.head.line).text.slice(0,i.head.ch))&&(a=Na(e,i.head.line,"smart"));a&&sn(e,"electricInput",e,i.head.line)}}}function Ia(e){for(var t=[],n=[],r=0;r<e.doc.sel.ranges.length;r++){var i=e.doc.sel.ranges[r].head.line,o={anchor:et(i,0),head:et(i+1,0)};n.push(o),t.push(e.getRange(o.anchor,o.head))}return{text:t,ranges:n}}function Fa(e,t,n,r){e.setAttribute("autocorrect",n?"":"off"),e.setAttribute("autocapitalize",r?"":"off"),e.setAttribute("spellcheck",!!t)}function _a(){var e=N("textarea",null,null,"position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none"),t=N("div",[e],null,"overflow: hidden; position: relative; width: 3px; height: 0px;");return s?e.style.width="1000px":e.setAttribute("wrap","off"),m&&(e.style.border="1px solid black"),Fa(e),t}function Wa(e,t,n,r,i){var o=t,a=n,l=Ke(e,t.line),s=i&&"rtl"==e.direction?-n:n;function c(o){var a,c;if("codepoint"==r){var u=l.text.charCodeAt(t.ch+(r>0?0:-1));a=isNaN(u)?null:new et(t.line,Math.max(0,Math.min(l.text.length,t.ch+n*(u>=55296&&u<56320?2:1))),-n)}else a=i?function(e,t,n,r){var i=ce(t,e.doc.direction);if(!i)return Jo(t,n,r);n.ch>=t.text.length?(n.ch=t.text.length,n.sticky="before"):n.ch<=0&&(n.ch=0,n.sticky="after");var o=le(i,n.ch,n.sticky),a=i[o];if("ltr"==e.doc.direction&&a.level%2==0&&(r>0?a.to>n.ch:a.from<n.ch))return Jo(t,n,r);var l,s=function(e,n){return Qo(t,e instanceof et?e.ch:e,n)},c=function(n){return e.options.lineWrapping?(l=l||zn(e,t),Qn(e,t,l,n)):{begin:0,end:t.text.length}},u=c("before"==n.sticky?s(n,-1):n.ch);if("rtl"==e.doc.direction||1==a.level){var f=1==a.level==r<0,d=s(n,f?1:-1);if(null!=d&&(f?d<=a.to&&d<=u.end:d>=a.from&&d>=u.begin)){var h=f?"before":"after";return new et(n.line,d,h)}}var p=function(e,t,r){for(var o=function(e,t){return t?new et(n.line,s(e,1),"before"):new et(n.line,e,"after")};e>=0&&e<i.length;e+=t){var a=i[e],l=t>0==(1!=a.level),c=l?r.begin:s(r.end,-1);if(a.from<=c&&c<a.to)return o(c,l);if(c=l?a.from:s(a.to,-1),r.begin<=c&&c<r.end)return o(c,l)}},m=p(o+r,r,u);if(m)return m;var g=r>0?u.end:s(u.begin,-1);return null==g||r>0&&g==t.text.length||!(m=p(r>0?0:i.length-1,r,c(g)))?null:m}(e.cm,l,t,n):Jo(l,t,n);if(null==a){if(o||(c=t.line+s)<e.first||c>=e.first+e.size||(t=new et(c,t.ch,t.sticky),!(l=Ke(e,c))))return!1;t=ea(i,e.cm,l,t.line,s)}else t=a;return!0}if("char"==r||"codepoint"==r)c();else if("column"==r)c(!0);else if("word"==r||"group"==r)for(var u=null,f="group"==r,d=e.cm&&e.cm.getHelper(t,"wordChars"),h=!0;!(n<0)||c(!h);h=!1){var p=l.text.charAt(t.ch)||"\n",m=ee(p,d)?"w":f&&"\n"==p?"n":!f||/\s/.test(p)?null:"p";if(!f||h||m||(m="s"),u&&u!=m){n<0&&(n=1,c(),t.sticky="after");break}if(m&&(u=m),n>0&&!c(!h))break}var g=oo(e,t,o,a,!0);return nt(o,g)&&(g.hitSide=!0),g}function Ha(e,t,n,r){var i,o,a=e.doc,l=t.left;if("page"==r){var s=Math.min(e.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight),c=Math.max(s-.5*rr(e.display),3);i=(n>0?t.bottom:t.top)+n*c}else"line"==r&&(i=n>0?t.bottom+3:t.top-3);for(;(o=Zn(e,l,i)).outside;){if(n<0?i<=0:i>=a.height){o.hitSide=!0;break}i+=5*n}return o}var Ra=function(e){this.cm=e,this.lastAnchorNode=this.lastAnchorOffset=this.lastFocusNode=this.lastFocusOffset=null,this.polling=new H,this.composing=null,this.gracePeriod=!1,this.readDOMTimeout=null};function Ba(e,t){var n=En(e,t.line);if(!n||n.hidden)return null;var r=Ke(e.doc,t.line),i=Nn(n,r,t.line),o=ce(r,e.doc.direction),a="left";o&&(a=le(o,t.ch)%2?"right":"left");var l=Fn(i.map,t.ch,a);return l.offset="right"==l.collapse?l.end:l.start,l}function ja(e,t){return t&&(e.bad=!0),e}function qa(e,t,n){var r;if(t==e.display.lineDiv){if(!(r=e.display.lineDiv.childNodes[n]))return ja(e.clipPos(et(e.display.viewTo-1)),!0);t=null,n=0}else for(r=t;;r=r.parentNode){if(!r||r==e.display.lineDiv)return null;if(r.parentNode&&r.parentNode==e.display.lineDiv)break}for(var i=0;i<e.display.view.length;i++){var o=e.display.view[i];if(o.node==r)return Ua(o,t,n)}}function Ua(e,t,n){var r=e.text.firstChild,i=!1;if(!t||!E(r,t))return ja(et(Ze(e.line),0),!0);if(t==r&&(i=!0,t=r.childNodes[n],n=0,!t)){var o=e.rest?G(e.rest):e.line;return ja(et(Ze(o),o.text.length),i)}var a=3==t.nodeType?t:null,l=t;for(a||1!=t.childNodes.length||3!=t.firstChild.nodeType||(a=t.firstChild,n&&(n=a.nodeValue.length));l.parentNode!=r;)l=l.parentNode;var s=e.measure,c=s.maps;function u(t,n,r){for(var i=-1;i<(c?c.length:0);i++)for(var o=i<0?s.map:c[i],a=0;a<o.length;a+=3){var l=o[a+2];if(l==t||l==n){var u=Ze(i<0?e.line:e.rest[i]),f=o[a]+r;return(r<0||l!=t)&&(f=o[a+(r?1:0)]),et(u,f)}}}var f=u(a,l,n);if(f)return ja(f,i);for(var d=l.nextSibling,h=a?a.nodeValue.length-n:0;d;d=d.nextSibling){if(f=u(d,d.firstChild,0))return ja(et(f.line,f.ch-h),i);h+=d.textContent.length}for(var p=l.previousSibling,m=n;p;p=p.previousSibling){if(f=u(p,p.firstChild,-1))return ja(et(f.line,f.ch+m),i);m+=p.textContent.length}}Ra.prototype.init=function(e){var t=this,n=this,r=n.cm,i=n.div=e.lineDiv;function o(e){for(var t=e.target;t;t=t.parentNode){if(t==i)return!0;if(/\bCodeMirror-(?:line)?widget\b/.test(t.className))break}return!1}function a(e){if(o(e)&&!me(r,e)){if(r.somethingSelected())Ea({lineWise:!1,text:r.getSelections()}),"cut"==e.type&&r.replaceSelection("",null,"cut");else{if(!r.options.lineWiseCopyCut)return;var t=Ia(r);Ea({lineWise:!0,text:t.text}),"cut"==e.type&&r.operation((function(){r.setSelections(t.ranges,0,j),r.replaceSelection("",null,"cut")}))}if(e.clipboardData){e.clipboardData.clearData();var a=Aa.text.join("\n");if(e.clipboardData.setData("Text",a),e.clipboardData.getData("Text")==a)return void e.preventDefault()}var l=_a(),s=l.firstChild;r.display.lineSpace.insertBefore(l,r.display.lineSpace.firstChild),s.value=Aa.text.join("\n");var c=document.activeElement;I(s),setTimeout((function(){r.display.lineSpace.removeChild(l),c.focus(),c==i&&n.showPrimarySelection()}),50)}}Fa(i,r.options.spellcheck,r.options.autocorrect,r.options.autocapitalize),fe(i,"paste",(function(e){!o(e)||me(r,e)||Pa(e,r)||l<=11&&setTimeout(ei(r,(function(){return t.updateFromDOM()})),20)})),fe(i,"compositionstart",(function(e){t.composing={data:e.data,done:!1}})),fe(i,"compositionupdate",(function(e){t.composing||(t.composing={data:e.data,done:!1})})),fe(i,"compositionend",(function(e){t.composing&&(e.data!=t.composing.data&&t.readFromDOMSoon(),t.composing.done=!0)})),fe(i,"touchstart",(function(){return n.forceCompositionEnd()})),fe(i,"input",(function(){t.composing||t.readFromDOMSoon()})),fe(i,"copy",a),fe(i,"cut",a)},Ra.prototype.screenReaderLabelChanged=function(e){e?this.div.setAttribute("aria-label",e):this.div.removeAttribute("aria-label")},Ra.prototype.prepareSelection=function(){var e=vr(this.cm,!1);return e.focus=document.activeElement==this.div,e},Ra.prototype.showSelection=function(e,t){e&&this.cm.display.view.length&&((e.focus||t)&&this.showPrimarySelection(),this.showMultipleSelections(e))},Ra.prototype.getSelection=function(){return this.cm.display.wrapper.ownerDocument.getSelection()},Ra.prototype.showPrimarySelection=function(){var e=this.getSelection(),t=this.cm,r=t.doc.sel.primary(),i=r.from(),o=r.to();if(t.display.viewTo==t.display.viewFrom||i.line>=t.display.viewTo||o.line<t.display.viewFrom)e.removeAllRanges();else{var a=qa(t,e.anchorNode,e.anchorOffset),l=qa(t,e.focusNode,e.focusOffset);if(!a||a.bad||!l||l.bad||0!=tt(ot(a,l),i)||0!=tt(it(a,l),o)){var s=t.display.view,c=i.line>=t.display.viewFrom&&Ba(t,i)||{node:s[0].measure.map[2],offset:0},u=o.line<t.display.viewTo&&Ba(t,o);if(!u){var f=s[s.length-1].measure,d=f.maps?f.maps[f.maps.length-1]:f.map;u={node:d[d.length-1],offset:d[d.length-2]-d[d.length-3]}}if(c&&u){var h,p=e.rangeCount&&e.getRangeAt(0);try{h=T(c.node,c.offset,u.offset,u.node)}catch(e){}h&&(!n&&t.state.focused?(e.collapse(c.node,c.offset),h.collapsed||(e.removeAllRanges(),e.addRange(h))):(e.removeAllRanges(),e.addRange(h)),p&&null==e.anchorNode?e.addRange(p):n&&this.startGracePeriod()),this.rememberSelection()}else e.removeAllRanges()}}},Ra.prototype.startGracePeriod=function(){var e=this;clearTimeout(this.gracePeriod),this.gracePeriod=setTimeout((function(){e.gracePeriod=!1,e.selectionChanged()&&e.cm.operation((function(){return e.cm.curOp.selectionChanged=!0}))}),20)},Ra.prototype.showMultipleSelections=function(e){O(this.cm.display.cursorDiv,e.cursors),O(this.cm.display.selectionDiv,e.selection)},Ra.prototype.rememberSelection=function(){var e=this.getSelection();this.lastAnchorNode=e.anchorNode,this.lastAnchorOffset=e.anchorOffset,this.lastFocusNode=e.focusNode,this.lastFocusOffset=e.focusOffset},Ra.prototype.selectionInEditor=function(){var e=this.getSelection();if(!e.rangeCount)return!1;var t=e.getRangeAt(0).commonAncestorContainer;return E(this.div,t)},Ra.prototype.focus=function(){"nocursor"!=this.cm.options.readOnly&&(this.selectionInEditor()&&document.activeElement==this.div||this.showSelection(this.prepareSelection(),!0),this.div.focus())},Ra.prototype.blur=function(){this.div.blur()},Ra.prototype.getField=function(){return this.div},Ra.prototype.supportsTouch=function(){return!0},Ra.prototype.receivedFocus=function(){var e=this;this.selectionInEditor()?this.pollSelection():Jr(this.cm,(function(){return e.cm.curOp.selectionChanged=!0})),this.polling.set(this.cm.options.pollInterval,(function t(){e.cm.state.focused&&(e.pollSelection(),e.polling.set(e.cm.options.pollInterval,t))}))},Ra.prototype.selectionChanged=function(){var e=this.getSelection();return e.anchorNode!=this.lastAnchorNode||e.anchorOffset!=this.lastAnchorOffset||e.focusNode!=this.lastFocusNode||e.focusOffset!=this.lastFocusOffset},Ra.prototype.pollSelection=function(){if(null==this.readDOMTimeout&&!this.gracePeriod&&this.selectionChanged()){var e=this.getSelection(),t=this.cm;if(g&&u&&this.cm.display.gutterSpecs.length&&function(e){for(var t=e;t;t=t.parentNode)if(/CodeMirror-gutter-wrapper/.test(t.className))return!0;return!1}(e.anchorNode))return this.cm.triggerOnKeyDown({type:"keydown",keyCode:8,preventDefault:Math.abs}),this.blur(),void this.focus();if(!this.composing){this.rememberSelection();var n=qa(t,e.anchorNode,e.anchorOffset),r=qa(t,e.focusNode,e.focusOffset);n&&r&&Jr(t,(function(){Ji(t.doc,Ti(n,r),j),(n.bad||r.bad)&&(t.curOp.selectionChanged=!0)}))}}},Ra.prototype.pollContent=function(){null!=this.readDOMTimeout&&(clearTimeout(this.readDOMTimeout),this.readDOMTimeout=null);var e,t,n,r=this.cm,i=r.display,o=r.doc.sel.primary(),a=o.from(),l=o.to();if(0==a.ch&&a.line>r.firstLine()&&(a=et(a.line-1,Ke(r.doc,a.line-1).length)),l.ch==Ke(r.doc,l.line).text.length&&l.line<r.lastLine()&&(l=et(l.line+1,0)),a.line<i.viewFrom||l.line>i.viewTo-1)return!1;a.line==i.viewFrom||0==(e=ur(r,a.line))?(t=Ze(i.view[0].line),n=i.view[0].node):(t=Ze(i.view[e].line),n=i.view[e-1].node.nextSibling);var s,c,u=ur(r,l.line);if(u==i.view.length-1?(s=i.viewTo-1,c=i.lineDiv.lastChild):(s=Ze(i.view[u+1].line)-1,c=i.view[u+1].node.previousSibling),!n)return!1;for(var f=r.doc.splitLines(function(e,t,n,r,i){var o="",a=!1,l=e.doc.lineSeparator(),s=!1;function c(){a&&(o+=l,s&&(o+=l),a=s=!1)}function u(e){e&&(c(),o+=e)}function f(t){if(1==t.nodeType){var n=t.getAttribute("cm-text");if(n)return void u(n);var o,d=t.getAttribute("cm-marker");if(d){var h=e.findMarks(et(r,0),et(i+1,0),(g=+d,function(e){return e.id==g}));return void(h.length&&(o=h[0].find(0))&&u($e(e.doc,o.from,o.to).join(l)))}if("false"==t.getAttribute("contenteditable"))return;var p=/^(pre|div|p|li|table|br)$/i.test(t.nodeName);if(!/^br$/i.test(t.nodeName)&&0==t.textContent.length)return;p&&c();for(var m=0;m<t.childNodes.length;m++)f(t.childNodes[m]);/^(pre|p)$/i.test(t.nodeName)&&(s=!0),p&&(a=!0)}else 3==t.nodeType&&u(t.nodeValue.replace(/\u200b/g,"").replace(/\u00a0/g," "));var g}for(;f(t),t!=n;)t=t.nextSibling,s=!1;return o}(r,n,c,t,s)),d=$e(r.doc,et(t,0),et(s,Ke(r.doc,s).text.length));f.length>1&&d.length>1;)if(G(f)==G(d))f.pop(),d.pop(),s--;else{if(f[0]!=d[0])break;f.shift(),d.shift(),t++}for(var h=0,p=0,m=f[0],g=d[0],v=Math.min(m.length,g.length);h<v&&m.charCodeAt(h)==g.charCodeAt(h);)++h;for(var y=G(f),b=G(d),x=Math.min(y.length-(1==f.length?h:0),b.length-(1==d.length?h:0));p<x&&y.charCodeAt(y.length-p-1)==b.charCodeAt(b.length-p-1);)++p;if(1==f.length&&1==d.length&&t==a.line)for(;h&&h>a.ch&&y.charCodeAt(y.length-p-1)==b.charCodeAt(b.length-p-1);)h--,p++;f[f.length-1]=y.slice(0,y.length-p).replace(/^\u200b+/,""),f[0]=f[0].slice(h).replace(/\u200b+$/,"");var w=et(t,h),k=et(s,d.length?G(d).length-p:0);return f.length>1||f[0]||tt(w,k)?(mo(r.doc,f,w,k,"+input"),!0):void 0},Ra.prototype.ensurePolled=function(){this.forceCompositionEnd()},Ra.prototype.reset=function(){this.forceCompositionEnd()},Ra.prototype.forceCompositionEnd=function(){this.composing&&(clearTimeout(this.readDOMTimeout),this.composing=null,this.updateFromDOM(),this.div.blur(),this.div.focus())},Ra.prototype.readFromDOMSoon=function(){var e=this;null==this.readDOMTimeout&&(this.readDOMTimeout=setTimeout((function(){if(e.readDOMTimeout=null,e.composing){if(!e.composing.done)return;e.composing=null}e.updateFromDOM()}),80))},Ra.prototype.updateFromDOM=function(){var e=this;!this.cm.isReadOnly()&&this.pollContent()||Jr(this.cm,(function(){return fr(e.cm)}))},Ra.prototype.setUneditable=function(e){e.contentEditable="false"},Ra.prototype.onKeyPress=function(e){0==e.charCode||this.composing||(e.preventDefault(),this.cm.isReadOnly()||ei(this.cm,za)(this.cm,String.fromCharCode(null==e.charCode?e.keyCode:e.charCode),0))},Ra.prototype.readOnlyChanged=function(e){this.div.contentEditable=String("nocursor"!=e)},Ra.prototype.onContextMenu=function(){},Ra.prototype.resetPosition=function(){},Ra.prototype.needsContentAttribute=!0;var Va=function(e){this.cm=e,this.prevInput="",this.pollingFast=!1,this.polling=new H,this.hasSelection=!1,this.composing=null};Va.prototype.init=function(e){var t=this,n=this,r=this.cm;this.createField(e);var i=this.textarea;function o(e){if(!me(r,e)){if(r.somethingSelected())Ea({lineWise:!1,text:r.getSelections()});else{if(!r.options.lineWiseCopyCut)return;var t=Ia(r);Ea({lineWise:!0,text:t.text}),"cut"==e.type?r.setSelections(t.ranges,null,j):(n.prevInput="",i.value=t.text.join("\n"),I(i))}"cut"==e.type&&(r.state.cutIncoming=+new Date)}}e.wrapper.insertBefore(this.wrapper,e.wrapper.firstChild),m&&(i.style.width="0px"),fe(i,"input",(function(){a&&l>=9&&t.hasSelection&&(t.hasSelection=null),n.poll()})),fe(i,"paste",(function(e){me(r,e)||Pa(e,r)||(r.state.pasteIncoming=+new Date,n.fastPoll())})),fe(i,"cut",o),fe(i,"copy",o),fe(e.scroller,"paste",(function(t){if(!kn(e,t)&&!me(r,t)){if(!i.dispatchEvent)return r.state.pasteIncoming=+new Date,void n.focus();var o=new Event("paste");o.clipboardData=t.clipboardData,i.dispatchEvent(o)}})),fe(e.lineSpace,"selectstart",(function(t){kn(e,t)||be(t)})),fe(i,"compositionstart",(function(){var e=r.getCursor("from");n.composing&&n.composing.range.clear(),n.composing={start:e,range:r.markText(e,r.getCursor("to"),{className:"CodeMirror-composing"})}})),fe(i,"compositionend",(function(){n.composing&&(n.poll(),n.composing.range.clear(),n.composing=null)}))},Va.prototype.createField=function(e){this.wrapper=_a(),this.textarea=this.wrapper.firstChild},Va.prototype.screenReaderLabelChanged=function(e){e?this.textarea.setAttribute("aria-label",e):this.textarea.removeAttribute("aria-label")},Va.prototype.prepareSelection=function(){var e=this.cm,t=e.display,n=e.doc,r=vr(e);if(e.options.moveInputWithCursor){var i=$n(e,n.sel.primary().head,"div"),o=t.wrapper.getBoundingClientRect(),a=t.lineDiv.getBoundingClientRect();r.teTop=Math.max(0,Math.min(t.wrapper.clientHeight-10,i.top+a.top-o.top)),r.teLeft=Math.max(0,Math.min(t.wrapper.clientWidth-10,i.left+a.left-o.left))}return r},Va.prototype.showSelection=function(e){var t=this.cm.display;O(t.cursorDiv,e.cursors),O(t.selectionDiv,e.selection),null!=e.teTop&&(this.wrapper.style.top=e.teTop+"px",this.wrapper.style.left=e.teLeft+"px")},Va.prototype.reset=function(e){if(!this.contextMenuPending&&!this.composing){var t=this.cm;if(t.somethingSelected()){this.prevInput="";var n=t.getSelection();this.textarea.value=n,t.state.focused&&I(this.textarea),a&&l>=9&&(this.hasSelection=n)}else e||(this.prevInput=this.textarea.value="",a&&l>=9&&(this.hasSelection=null))}},Va.prototype.getField=function(){return this.textarea},Va.prototype.supportsTouch=function(){return!1},Va.prototype.focus=function(){if("nocursor"!=this.cm.options.readOnly&&(!v||z()!=this.textarea))try{this.textarea.focus()}catch(e){}},Va.prototype.blur=function(){this.textarea.blur()},Va.prototype.resetPosition=function(){this.wrapper.style.top=this.wrapper.style.left=0},Va.prototype.receivedFocus=function(){this.slowPoll()},Va.prototype.slowPoll=function(){var e=this;this.pollingFast||this.polling.set(this.cm.options.pollInterval,(function(){e.poll(),e.cm.state.focused&&e.slowPoll()}))},Va.prototype.fastPoll=function(){var e=!1,t=this;t.pollingFast=!0,t.polling.set(20,(function n(){t.poll()||e?(t.pollingFast=!1,t.slowPoll()):(e=!0,t.polling.set(60,n))}))},Va.prototype.poll=function(){var e=this,t=this.cm,n=this.textarea,r=this.prevInput;if(this.contextMenuPending||!t.state.focused||ze(n)&&!r&&!this.composing||t.isReadOnly()||t.options.disableInput||t.state.keySeq)return!1;var i=n.value;if(i==r&&!t.somethingSelected())return!1;if(a&&l>=9&&this.hasSelection===i||y&&/[\uf700-\uf7ff]/.test(i))return t.display.input.reset(),!1;if(t.doc.sel==t.display.selForContextMenu){var o=i.charCodeAt(0);if(8203!=o||r||(r="​"),8666==o)return this.reset(),this.cm.execCommand("undo")}for(var s=0,c=Math.min(r.length,i.length);s<c&&r.charCodeAt(s)==i.charCodeAt(s);)++s;return Jr(t,(function(){za(t,i.slice(s),r.length-s,null,e.composing?"*compose":null),i.length>1e3||i.indexOf("\n")>-1?n.value=e.prevInput="":e.prevInput=i,e.composing&&(e.composing.range.clear(),e.composing.range=t.markText(e.composing.start,t.getCursor("to"),{className:"CodeMirror-composing"}))})),!0},Va.prototype.ensurePolled=function(){this.pollingFast&&this.poll()&&(this.pollingFast=!1)},Va.prototype.onKeyPress=function(){a&&l>=9&&(this.hasSelection=null),this.fastPoll()},Va.prototype.onContextMenu=function(e){var t=this,n=t.cm,r=n.display,i=t.textarea;t.contextMenuPending&&t.contextMenuPending();var o=cr(n,e),c=r.scroller.scrollTop;if(o&&!f){n.options.resetSelectionOnContextMenu&&-1==n.doc.sel.contains(o)&&ei(n,Ji)(n.doc,Ti(o),j);var u,d=i.style.cssText,h=t.wrapper.style.cssText,p=t.wrapper.offsetParent.getBoundingClientRect();if(t.wrapper.style.cssText="position: static",i.style.cssText="position: absolute; width: 30px; height: 30px;\n top: "+(e.clientY-p.top-5)+"px; left: "+(e.clientX-p.left-5)+"px;\n z-index: 1000; background: "+(a?"rgba(255, 255, 255, .05)":"transparent")+";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);",s&&(u=window.scrollY),r.input.focus(),s&&window.scrollTo(null,u),r.input.reset(),n.somethingSelected()||(i.value=t.prevInput=" "),t.contextMenuPending=v,r.selForContextMenu=n.doc.sel,clearTimeout(r.detectingSelectAll),a&&l>=9&&g(),C){ke(e);var m=function(){he(window,"mouseup",m),setTimeout(v,20)};fe(window,"mouseup",m)}else setTimeout(v,50)}function g(){if(null!=i.selectionStart){var e=n.somethingSelected(),o="​"+(e?i.value:"");i.value="⇚",i.value=o,t.prevInput=e?"":"​",i.selectionStart=1,i.selectionEnd=o.length,r.selForContextMenu=n.doc.sel}}function v(){if(t.contextMenuPending==v&&(t.contextMenuPending=!1,t.wrapper.style.cssText=h,i.style.cssText=d,a&&l<9&&r.scrollbars.setScrollTop(r.scroller.scrollTop=c),null!=i.selectionStart)){(!a||a&&l<9)&&g();var e=0,o=function(){r.selForContextMenu==n.doc.sel&&0==i.selectionStart&&i.selectionEnd>0&&"​"==t.prevInput?ei(n,lo)(n):e++<10?r.detectingSelectAll=setTimeout(o,500):(r.selForContextMenu=null,r.input.reset())};r.detectingSelectAll=setTimeout(o,200)}}},Va.prototype.readOnlyChanged=function(e){e||this.reset(),this.textarea.disabled="nocursor"==e,this.textarea.readOnly=!!e},Va.prototype.setUneditable=function(){},Va.prototype.needsContentAttribute=!1,function(e){var t=e.optionHandlers;function n(n,r,i,o){e.defaults[n]=r,i&&(t[n]=o?function(e,t,n){n!=ka&&i(e,t,n)}:i)}e.defineOption=n,e.Init=ka,n("value","",(function(e,t){return e.setValue(t)}),!0),n("mode",null,(function(e,t){e.doc.modeOption=t,Ai(e)}),!0),n("indentUnit",2,Ai,!0),n("indentWithTabs",!1),n("smartIndent",!0),n("tabSize",4,(function(e){Ei(e),Rn(e),fr(e)}),!0),n("lineSeparator",null,(function(e,t){if(e.doc.lineSep=t,t){var n=[],r=e.doc.first;e.doc.iter((function(e){for(var i=0;;){var o=e.text.indexOf(t,i);if(-1==o)break;i=o+t.length,n.push(et(r,o))}r++}));for(var i=n.length-1;i>=0;i--)mo(e.doc,t,n[i],et(n[i].line,n[i].ch+t.length))}})),n("specialChars",/[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200c\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g,(function(e,t,n){e.state.specialChars=new RegExp(t.source+(t.test("\t")?"":"|\t"),"g"),n!=ka&&e.refresh()})),n("specialCharPlaceholder",Qt,(function(e){return e.refresh()}),!0),n("electricChars",!0),n("inputStyle",v?"contenteditable":"textarea",(function(){throw new Error("inputStyle can not (yet) be changed in a running editor")}),!0),n("spellcheck",!1,(function(e,t){return e.getInputField().spellcheck=t}),!0),n("autocorrect",!1,(function(e,t){return e.getInputField().autocorrect=t}),!0),n("autocapitalize",!1,(function(e,t){return e.getInputField().autocapitalize=t}),!0),n("rtlMoveVisually",!x),n("wholeLineUpdateBefore",!0),n("theme","default",(function(e){wa(e),mi(e)}),!0),n("keyMap","default",(function(e,t,n){var r=Zo(t),i=n!=ka&&Zo(n);i&&i.detach&&i.detach(e,r),r.attach&&r.attach(e,i||null)})),n("extraKeys",null),n("configureMouse",null),n("lineWrapping",!1,La,!0),n("gutters",[],(function(e,t){e.display.gutterSpecs=hi(t,e.options.lineNumbers),mi(e)}),!0),n("fixedGutter",!0,(function(e,t){e.display.gutters.style.left=t?ar(e.display)+"px":"0",e.refresh()}),!0),n("coverGutterNextToScrollbar",!1,(function(e){return Br(e)}),!0),n("scrollbarStyle","native",(function(e){Ur(e),Br(e),e.display.scrollbars.setScrollTop(e.doc.scrollTop),e.display.scrollbars.setScrollLeft(e.doc.scrollLeft)}),!0),n("lineNumbers",!1,(function(e,t){e.display.gutterSpecs=hi(e.options.gutters,t),mi(e)}),!0),n("firstLineNumber",1,mi,!0),n("lineNumberFormatter",(function(e){return e}),mi,!0),n("showCursorWhenSelecting",!1,gr,!0),n("resetSelectionOnContextMenu",!0),n("lineWiseCopyCut",!0),n("pasteLinesPerSelection",!0),n("selectionsMayTouch",!1),n("readOnly",!1,(function(e,t){"nocursor"==t&&(Tr(e),e.display.input.blur()),e.display.input.readOnlyChanged(t)})),n("screenReaderLabel",null,(function(e,t){t=""===t?null:t,e.display.input.screenReaderLabelChanged(t)})),n("disableInput",!1,(function(e,t){t||e.display.input.reset()}),!0),n("dragDrop",!0,Ta),n("allowDropFileTypes",null),n("cursorBlinkRate",530),n("cursorScrollMargin",0),n("cursorHeight",1,gr,!0),n("singleCursorHeightPerLine",!0,gr,!0),n("workTime",100),n("workDelay",100),n("flattenSpans",!0,Ei,!0),n("addModeClass",!1,Ei,!0),n("pollInterval",100),n("undoDepth",200,(function(e,t){return e.doc.history.undoDepth=t})),n("historyEventDelay",1250),n("viewportMargin",10,(function(e){return e.refresh()}),!0),n("maxHighlightLength",1e4,Ei,!0),n("moveInputWithCursor",!0,(function(e,t){t||e.display.input.resetPosition()})),n("tabindex",null,(function(e,t){return e.display.input.getField().tabIndex=t||""})),n("autofocus",null),n("direction","ltr",(function(e,t){return e.doc.setDirection(t)}),!0),n("phrases",null)}(Ma),function(e){var t=e.optionHandlers,n=e.helpers={};e.prototype={constructor:e,focus:function(){window.focus(),this.display.input.focus()},setOption:function(e,n){var r=this.options,i=r[e];r[e]==n&&"mode"!=e||(r[e]=n,t.hasOwnProperty(e)&&ei(this,t[e])(this,n,i),pe(this,"optionChange",this,e))},getOption:function(e){return this.options[e]},getDoc:function(){return this.doc},addKeyMap:function(e,t){this.state.keyMaps[t?"push":"unshift"](Zo(e))},removeKeyMap:function(e){for(var t=this.state.keyMaps,n=0;n<t.length;++n)if(t[n]==e||t[n].name==e)return t.splice(n,1),!0},addOverlay:ti((function(t,n){var r=t.token?t:e.getMode(this.options,t);if(r.startState)throw new Error("Overlays may not be stateful.");!function(e,t,n){for(var r=0,i=n(t);r<e.length&&n(e[r])<=i;)r++;e.splice(r,0,t)}(this.state.overlays,{mode:r,modeSpec:t,opaque:n&&n.opaque,priority:n&&n.priority||0},(function(e){return e.priority})),this.state.modeGen++,fr(this)})),removeOverlay:ti((function(e){for(var t=this.state.overlays,n=0;n<t.length;++n){var r=t[n].modeSpec;if(r==e||"string"==typeof e&&r.name==e)return t.splice(n,1),this.state.modeGen++,void fr(this)}})),indentLine:ti((function(e,t,n){"string"!=typeof t&&"number"!=typeof t&&(t=null==t?this.options.smartIndent?"smart":"prev":t?"add":"subtract"),Qe(this.doc,e)&&Na(this,e,t,n)})),indentSelection:ti((function(e){for(var t=this.doc.sel.ranges,n=-1,r=0;r<t.length;r++){var i=t[r];if(i.empty())i.head.line>n&&(Na(this,i.head.line,e,!0),n=i.head.line,r==this.doc.sel.primIndex&&Er(this));else{var o=i.from(),a=i.to(),l=Math.max(n,o.line);n=Math.min(this.lastLine(),a.line-(a.ch?0:1))+1;for(var s=l;s<n;++s)Na(this,s,e);var c=this.doc.sel.ranges;0==o.ch&&t.length==c.length&&c[r].from().ch>0&&Zi(this.doc,r,new Ci(o,c[r].to()),j)}}})),getTokenAt:function(e,t){return yt(this,e,t)},getLineTokens:function(e,t){return yt(this,et(e),t,!0)},getTokenTypeAt:function(e){e=lt(this.doc,e);var t,n=dt(this,Ke(this.doc,e.line)),r=0,i=(n.length-1)/2,o=e.ch;if(0==o)t=n[2];else for(;;){var a=r+i>>1;if((a?n[2*a-1]:0)>=o)i=a;else{if(!(n[2*a+1]<o)){t=n[2*a+2];break}r=a+1}}var l=t?t.indexOf("overlay "):-1;return l<0?t:0==l?null:t.slice(0,l-1)},getModeAt:function(t){var n=this.doc.mode;return n.innerMode?e.innerMode(n,this.getTokenAt(t).state).mode:n},getHelper:function(e,t){return this.getHelpers(e,t)[0]},getHelpers:function(e,t){var r=[];if(!n.hasOwnProperty(t))return r;var i=n[t],o=this.getModeAt(e);if("string"==typeof o[t])i[o[t]]&&r.push(i[o[t]]);else if(o[t])for(var a=0;a<o[t].length;a++){var l=i[o[t][a]];l&&r.push(l)}else o.helperType&&i[o.helperType]?r.push(i[o.helperType]):i[o.name]&&r.push(i[o.name]);for(var s=0;s<i._global.length;s++){var c=i._global[s];c.pred(o,this)&&-1==R(r,c.val)&&r.push(c.val)}return r},getStateAfter:function(e,t){var n=this.doc;return ht(this,(e=at(n,null==e?n.first+n.size-1:e))+1,t).state},cursorCoords:function(e,t){var n=this.doc.sel.primary();return $n(this,null==e?n.head:"object"==typeof e?lt(this.doc,e):e?n.from():n.to(),t||"page")},charCoords:function(e,t){return Kn(this,lt(this.doc,e),t||"page")},coordsChar:function(e,t){return Zn(this,(e=Vn(this,e,t||"page")).left,e.top)},lineAtHeight:function(e,t){return e=Vn(this,{top:e,left:0},t||"page").top,Ye(this.doc,e+this.display.viewOffset)},heightAtLine:function(e,t,n){var r,i=!1;if("number"==typeof e){var o=this.doc.first+this.doc.size-1;e<this.doc.first?e=this.doc.first:e>o&&(e=o,i=!0),r=Ke(this.doc,e)}else r=e;return Un(this,r,{top:0,left:0},t||"page",n||i).top+(i?this.doc.height-qt(r):0)},defaultTextHeight:function(){return rr(this.display)},defaultCharWidth:function(){return ir(this.display)},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(e,t,n,r,i){var o,a,l,s=this.display,c=(e=$n(this,lt(this.doc,e))).bottom,u=e.left;if(t.style.position="absolute",t.setAttribute("cm-ignore-events","true"),this.display.input.setUneditable(t),s.sizer.appendChild(t),"over"==r)c=e.top;else if("above"==r||"near"==r){var f=Math.max(s.wrapper.clientHeight,this.doc.height),d=Math.max(s.sizer.clientWidth,s.lineSpace.clientWidth);("above"==r||e.bottom+t.offsetHeight>f)&&e.top>t.offsetHeight?c=e.top-t.offsetHeight:e.bottom+t.offsetHeight<=f&&(c=e.bottom),u+t.offsetWidth>d&&(u=d-t.offsetWidth)}t.style.top=c+"px",t.style.left=t.style.right="","right"==i?(u=s.sizer.clientWidth-t.offsetWidth,t.style.right="0px"):("left"==i?u=0:"middle"==i&&(u=(s.sizer.clientWidth-t.offsetWidth)/2),t.style.left=u+"px"),n&&(o=this,a={left:u,top:c,right:u+t.offsetWidth,bottom:c+t.offsetHeight},null!=(l=Nr(o,a)).scrollTop&&Ir(o,l.scrollTop),null!=l.scrollLeft&&_r(o,l.scrollLeft))},triggerOnKeyDown:ti(ua),triggerOnKeyPress:ti(da),triggerOnKeyUp:fa,triggerOnMouseDown:ti(ga),execCommand:function(e){if(ta.hasOwnProperty(e))return ta[e].call(null,this)},triggerElectric:ti((function(e){Da(this,e)})),findPosH:function(e,t,n,r){var i=1;t<0&&(i=-1,t=-t);for(var o=lt(this.doc,e),a=0;a<t&&!(o=Wa(this.doc,o,i,n,r)).hitSide;++a);return o},moveH:ti((function(e,t){var n=this;this.extendSelectionsBy((function(r){return n.display.shift||n.doc.extend||r.empty()?Wa(n.doc,r.head,e,t,n.options.rtlMoveVisually):e<0?r.from():r.to()}),U)})),deleteH:ti((function(e,t){var n=this.doc.sel,r=this.doc;n.somethingSelected()?r.replaceSelection("",null,"+delete"):Yo(this,(function(n){var i=Wa(r,n.head,e,t,!1);return e<0?{from:i,to:n.head}:{from:n.head,to:i}}))})),findPosV:function(e,t,n,r){var i=1,o=r;t<0&&(i=-1,t=-t);for(var a=lt(this.doc,e),l=0;l<t;++l){var s=$n(this,a,"div");if(null==o?o=s.left:s.left=o,(a=Ha(this,s,i,n)).hitSide)break}return a},moveV:ti((function(e,t){var n=this,r=this.doc,i=[],o=!this.display.shift&&!r.extend&&r.sel.somethingSelected();if(r.extendSelectionsBy((function(a){if(o)return e<0?a.from():a.to();var l=$n(n,a.head,"div");null!=a.goalColumn&&(l.left=a.goalColumn),i.push(l.left);var s=Ha(n,l,e,t);return"page"==t&&a==r.sel.primary()&&Ar(n,Kn(n,s,"div").top-l.top),s}),U),i.length)for(var a=0;a<r.sel.ranges.length;a++)r.sel.ranges[a].goalColumn=i[a]})),findWordAt:function(e){var t=Ke(this.doc,e.line).text,n=e.ch,r=e.ch;if(t){var i=this.getHelper(e,"wordChars");"before"!=e.sticky&&r!=t.length||!n?++r:--n;for(var o=t.charAt(n),a=ee(o,i)?function(e){return ee(e,i)}:/\s/.test(o)?function(e){return/\s/.test(e)}:function(e){return!/\s/.test(e)&&!ee(e)};n>0&&a(t.charAt(n-1));)--n;for(;r<t.length&&a(t.charAt(r));)++r}return new Ci(et(e.line,n),et(e.line,r))},toggleOverwrite:function(e){null!=e&&e==this.state.overwrite||((this.state.overwrite=!this.state.overwrite)?P(this.display.cursorDiv,"CodeMirror-overwrite"):L(this.display.cursorDiv,"CodeMirror-overwrite"),pe(this,"overwriteToggle",this,this.state.overwrite))},hasFocus:function(){return this.display.input.getField()==z()},isReadOnly:function(){return!(!this.options.readOnly&&!this.doc.cantEdit)},scrollTo:ti((function(e,t){zr(this,e,t)})),getScrollInfo:function(){var e=this.display.scroller;return{left:e.scrollLeft,top:e.scrollTop,height:e.scrollHeight-Ln(this)-this.display.barHeight,width:e.scrollWidth-Ln(this)-this.display.barWidth,clientHeight:On(this),clientWidth:Mn(this)}},scrollIntoView:ti((function(e,t){null==e?(e={from:this.doc.sel.primary().head,to:null},null==t&&(t=this.options.cursorScrollMargin)):"number"==typeof e?e={from:et(e,0),to:null}:null==e.from&&(e={from:e,to:null}),e.to||(e.to=e.from),e.margin=t||0,null!=e.from.line?function(e,t){Pr(e),e.curOp.scrollToPos=t}(this,e):Dr(this,e.from,e.to,e.margin)})),setSize:ti((function(e,t){var n=this,r=function(e){return"number"==typeof e||/^\d+$/.test(String(e))?e+"px":e};null!=e&&(this.display.wrapper.style.width=r(e)),null!=t&&(this.display.wrapper.style.height=r(t)),this.options.lineWrapping&&Hn(this);var i=this.display.viewFrom;this.doc.iter(i,this.display.viewTo,(function(e){if(e.widgets)for(var t=0;t<e.widgets.length;t++)if(e.widgets[t].noHScroll){dr(n,i,"widget");break}++i})),this.curOp.forceUpdate=!0,pe(this,"refresh",this)})),operation:function(e){return Jr(this,e)},startOperation:function(){return Kr(this)},endOperation:function(){return $r(this)},refresh:ti((function(){var e=this.display.cachedTextHeight;fr(this),this.curOp.forceUpdate=!0,Rn(this),zr(this,this.doc.scrollLeft,this.doc.scrollTop),ci(this.display),(null==e||Math.abs(e-rr(this.display))>.5||this.options.lineWrapping)&&sr(this),pe(this,"refresh",this)})),swapDoc:ti((function(e){var t=this.doc;return t.cm=null,this.state.selectingText&&this.state.selectingText(),Ii(this,e),Rn(this),this.display.input.reset(),zr(this,e.scrollLeft,e.scrollTop),this.curOp.forceScroll=!0,sn(this,"swapDoc",this,t),t})),phrase:function(e){var t=this.options.phrases;return t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]:e},getInputField:function(){return this.display.input.getField()},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}},ye(e),e.registerHelper=function(t,r,i){n.hasOwnProperty(t)||(n[t]=e[t]={_global:[]}),n[t][r]=i},e.registerGlobalHelper=function(t,r,i,o){e.registerHelper(t,r,o),n[t]._global.push({pred:i,val:o})}}(Ma);var Ka="iter insert remove copy getEditor constructor".split(" ");for(var $a in Eo.prototype)Eo.prototype.hasOwnProperty($a)&&R(Ka,$a)<0&&(Ma.prototype[$a]=function(e){return function(){return e.apply(this.doc,arguments)}}(Eo.prototype[$a]));return ye(Eo),Ma.inputStyles={textarea:Va,contenteditable:Ra},Ma.defineMode=function(e){Ma.defaults.mode||"null"==e||(Ma.defaults.mode=e),_e.apply(this,arguments)},Ma.defineMIME=function(e,t){Fe[e]=t},Ma.defineMode("null",(function(){return{token:function(e){return e.skipToEnd()}}})),Ma.defineMIME("text/plain","null"),Ma.defineExtension=function(e,t){Ma.prototype[e]=t},Ma.defineDocExtension=function(e,t){Eo.prototype[e]=t},Ma.fromTextArea=function(e,t){if((t=t?_(t):{}).value=e.value,!t.tabindex&&e.tabIndex&&(t.tabindex=e.tabIndex),!t.placeholder&&e.placeholder&&(t.placeholder=e.placeholder),null==t.autofocus){var n=z();t.autofocus=n==e||null!=e.getAttribute("autofocus")&&n==document.body}function r(){e.value=l.getValue()}var i;if(e.form&&(fe(e.form,"submit",r),!t.leaveSubmitMethodAlone)){var o=e.form;i=o.submit;try{var a=o.submit=function(){r(),o.submit=i,o.submit(),o.submit=a}}catch(e){}}t.finishInit=function(n){n.save=r,n.getTextArea=function(){return e},n.toTextArea=function(){n.toTextArea=isNaN,r(),e.parentNode.removeChild(n.getWrapperElement()),e.style.display="",e.form&&(he(e.form,"submit",r),t.leaveSubmitMethodAlone||"function"!=typeof e.form.submit||(e.form.submit=i))}},e.style.display="none";var l=Ma((function(t){return e.parentNode.insertBefore(t,e.nextSibling)}),t);return l},function(e){e.off=he,e.on=fe,e.wheelEventPixels=xi,e.Doc=Eo,e.splitLines=Ee,e.countColumn=W,e.findColumn=V,e.isWordChar=J,e.Pass=B,e.signal=pe,e.Line=Kt,e.changeEnd=Li,e.scrollbarModel=qr,e.Pos=et,e.cmpPos=tt,e.modes=Ie,e.mimeModes=Fe,e.resolveMode=We,e.getMode=He,e.modeExtensions=Re,e.extendMode=Be,e.copyState=je,e.startState=Ue,e.innerMode=qe,e.commands=ta,e.keyMap=qo,e.keyName=Xo,e.isModifierKey=$o,e.lookupKey=Ko,e.normalizeKeyMap=Vo,e.StringStream=Ve,e.SharedTextMarker=Mo,e.TextMarker=To,e.LineWidget=ko,e.e_preventDefault=be,e.e_stopPropagation=xe,e.e_stop=ke,e.addClass=P,e.contains=E,e.rmClass=L,e.keyNames=Ho}(Ma),Ma.version="5.58.1",Ma}()},function(e,t,n){!function(e){"use strict";var t,n,r=e.Pos;function i(e,t){for(var n=function(e){var t=e.flags;return null!=t?t:(e.ignoreCase?"i":"")+(e.global?"g":"")+(e.multiline?"m":"")}(e),r=n,i=0;i<t.length;i++)-1==r.indexOf(t.charAt(i))&&(r+=t.charAt(i));return n==r?e:new RegExp(e.source,r)}function o(e,t,n){t=i(t,"g");for(var o=n.line,a=n.ch,l=e.lastLine();o<=l;o++,a=0){t.lastIndex=a;var s=e.getLine(o),c=t.exec(s);if(c)return{from:r(o,c.index),to:r(o,c.index+c[0].length),match:c}}}function a(e,t,n){if(!function(e){return/\\s|\\n|\n|\\W|\\D|\[\^/.test(e.source)}(t))return o(e,t,n);t=i(t,"gm");for(var a,l=1,s=n.line,c=e.lastLine();s<=c;){for(var u=0;u<l&&!(s>c);u++){var f=e.getLine(s++);a=null==a?f:a+"\n"+f}l*=2,t.lastIndex=n.ch;var d=t.exec(a);if(d){var h=a.slice(0,d.index).split("\n"),p=d[0].split("\n"),m=n.line+h.length-1,g=h[h.length-1].length;return{from:r(m,g),to:r(m+p.length-1,1==p.length?g+p[0].length:p[p.length-1].length),match:d}}}}function l(e,t){for(var n,r=0;;){t.lastIndex=r;var i=t.exec(e);if(!i)return n;if((r=(n=i).index+(n[0].length||1))==e.length)return n}}function s(e,t,n){t=i(t,"g");for(var o=n.line,a=n.ch,s=e.firstLine();o>=s;o--,a=-1){var c=e.getLine(o);a>-1&&(c=c.slice(0,a));var u=l(c,t);if(u)return{from:r(o,u.index),to:r(o,u.index+u[0].length),match:u}}}function c(e,t,n){t=i(t,"gm");for(var o,a=1,s=n.line,c=e.firstLine();s>=c;){for(var u=0;u<a;u++){var f=e.getLine(s--);o=null==o?f.slice(0,n.ch):f+"\n"+o}a*=2;var d=l(o,t);if(d){var h=o.slice(0,d.index).split("\n"),p=d[0].split("\n"),m=s+h.length,g=h[h.length-1].length;return{from:r(m,g),to:r(m+p.length-1,1==p.length?g+p[0].length:p[p.length-1].length),match:d}}}}function u(e,t,n,r){if(e.length==t.length)return n;for(var i=0,o=n+Math.max(0,e.length-t.length);;){if(i==o)return i;var a=i+o>>1,l=r(e.slice(0,a)).length;if(l==n)return a;l>n?o=a:i=a+1}}function f(e,i,o,a){if(!i.length)return null;var l=a?t:n,s=l(i).split(/\r|\n\r?/);e:for(var c=o.line,f=o.ch,d=e.lastLine()+1-s.length;c<=d;c++,f=0){var h=e.getLine(c).slice(f),p=l(h);if(1==s.length){var m=p.indexOf(s[0]);if(-1==m)continue e;return o=u(h,p,m,l)+f,{from:r(c,u(h,p,m,l)+f),to:r(c,u(h,p,m+s[0].length,l)+f)}}var g=p.length-s[0].length;if(p.slice(g)==s[0]){for(var v=1;v<s.length-1;v++)if(l(e.getLine(c+v))!=s[v])continue e;var y=e.getLine(c+s.length-1),b=l(y),x=s[s.length-1];if(b.slice(0,x.length)==x)return{from:r(c,u(h,p,g,l)+f),to:r(c+s.length-1,u(y,b,x.length,l))}}}}function d(e,i,o,a){if(!i.length)return null;var l=a?t:n,s=l(i).split(/\r|\n\r?/);e:for(var c=o.line,f=o.ch,d=e.firstLine()-1+s.length;c>=d;c--,f=-1){var h=e.getLine(c);f>-1&&(h=h.slice(0,f));var p=l(h);if(1==s.length){var m=p.lastIndexOf(s[0]);if(-1==m)continue e;return{from:r(c,u(h,p,m,l)),to:r(c,u(h,p,m+s[0].length,l))}}var g=s[s.length-1];if(p.slice(0,g.length)==g){var v=1;for(o=c-s.length+1;v<s.length-1;v++)if(l(e.getLine(o+v))!=s[v])continue e;var y=e.getLine(c+1-s.length),b=l(y);if(b.slice(b.length-s[0].length)==s[0])return{from:r(c+1-s.length,u(y,b,y.length-s[0].length,l)),to:r(c,u(h,p,g.length,l))}}}}function h(e,t,n,l){var u;this.atOccurrence=!1,this.doc=e,n=n?e.clipPos(n):r(0,0),this.pos={from:n,to:n},"object"==typeof l?u=l.caseFold:(u=l,l=null),"string"==typeof t?(null==u&&(u=!1),this.matches=function(n,r){return(n?d:f)(e,t,r,u)}):(t=i(t,"gm"),l&&!1===l.multiline?this.matches=function(n,r){return(n?s:o)(e,t,r)}:this.matches=function(n,r){return(n?c:a)(e,t,r)})}String.prototype.normalize?(t=function(e){return e.normalize("NFD").toLowerCase()},n=function(e){return e.normalize("NFD")}):(t=function(e){return e.toLowerCase()},n=function(e){return e}),h.prototype={findNext:function(){return this.find(!1)},findPrevious:function(){return this.find(!0)},find:function(t){for(var n=this.matches(t,this.doc.clipPos(t?this.pos.from:this.pos.to));n&&0==e.cmpPos(n.from,n.to);)t?n.from.ch?n.from=r(n.from.line,n.from.ch-1):n=n.from.line==this.doc.firstLine()?null:this.matches(t,this.doc.clipPos(r(n.from.line-1))):n.to.ch<this.doc.getLine(n.to.line).length?n.to=r(n.to.line,n.to.ch+1):n=n.to.line==this.doc.lastLine()?null:this.matches(t,r(n.to.line+1,0));if(n)return this.pos=n,this.atOccurrence=!0,this.pos.match||!0;var i=r(t?this.doc.firstLine():this.doc.lastLine()+1,0);return this.pos={from:i,to:i},this.atOccurrence=!1},from:function(){if(this.atOccurrence)return this.pos.from},to:function(){if(this.atOccurrence)return this.pos.to},replace:function(t,n){if(this.atOccurrence){var i=e.splitLines(t);this.doc.replaceRange(i,this.pos.from,this.pos.to,n),this.pos.to=r(this.pos.from.line+i.length-1,i[i.length-1].length+(1==i.length?this.pos.from.ch:0))}}},e.defineExtension("getSearchCursor",(function(e,t,n){return new h(this.doc,e,t,n)})),e.defineDocExtension("getSearchCursor",(function(e,t,n){return new h(this,e,t,n)})),e.defineExtension("selectMatches",(function(t,n){for(var r=[],i=this.getSearchCursor(t,this.getCursor("from"),n);i.findNext()&&!(e.cmpPos(i.to(),this.getCursor("to"))>0);)r.push({anchor:i.from(),head:i.to()});r.length&&this.setSelections(r,0)}))}(n(0))},function(e,t,n){!function(e){"use strict";e.defineMode("javascript",(function(t,n){var r,i,o=t.indentUnit,a=n.statementIndent,l=n.jsonld,s=n.json||l,c=n.typescript,u=n.wordCharacters||/[\w$\xa1-\uffff]/,f=function(){function e(e){return{type:e,style:"keyword"}}var t=e("keyword a"),n=e("keyword b"),r=e("keyword c"),i=e("keyword d"),o=e("operator"),a={type:"atom",style:"atom"};return{if:e("if"),while:t,with:t,else:n,do:n,try:n,finally:n,return:i,break:i,continue:i,new:e("new"),delete:r,void:r,throw:r,debugger:e("debugger"),var:e("var"),const:e("var"),let:e("var"),function:e("function"),catch:e("catch"),for:e("for"),switch:e("switch"),case:e("case"),default:e("default"),in:o,typeof:o,instanceof:o,true:a,false:a,null:a,undefined:a,NaN:a,Infinity:a,this:e("this"),class:e("class"),super:e("atom"),yield:r,export:e("export"),import:e("import"),extends:r,await:r}}(),d=/[+\-*&%=<>!?|~^@]/,h=/^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;function p(e,t,n){return r=e,i=n,t}function m(e,t){var n,r=e.next();if('"'==r||"'"==r)return t.tokenize=(n=r,function(e,t){var r,i=!1;if(l&&"@"==e.peek()&&e.match(h))return t.tokenize=m,p("jsonld-keyword","meta");for(;null!=(r=e.next())&&(r!=n||i);)i=!i&&"\\"==r;return i||(t.tokenize=m),p("string","string")}),t.tokenize(e,t);if("."==r&&e.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/))return p("number","number");if("."==r&&e.match(".."))return p("spread","meta");if(/[\[\]{}\(\),;\:\.]/.test(r))return p(r);if("="==r&&e.eat(">"))return p("=>","operator");if("0"==r&&e.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/))return p("number","number");if(/\d/.test(r))return e.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/),p("number","number");if("/"==r)return e.eat("*")?(t.tokenize=g,g(e,t)):e.eat("/")?(e.skipToEnd(),p("comment","comment")):$e(e,t,1)?(function(e){for(var t,n=!1,r=!1;null!=(t=e.next());){if(!n){if("/"==t&&!r)return;"["==t?r=!0:r&&"]"==t&&(r=!1)}n=!n&&"\\"==t}}(e),e.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/),p("regexp","string-2")):(e.eat("="),p("operator","operator",e.current()));if("`"==r)return t.tokenize=v,v(e,t);if("#"==r&&"!"==e.peek())return e.skipToEnd(),p("meta","meta");if("#"==r&&e.eatWhile(u))return p("variable","property");if("<"==r&&e.match("!--")||"-"==r&&e.match("->")&&!/\S/.test(e.string.slice(0,e.start)))return e.skipToEnd(),p("comment","comment");if(d.test(r))return">"==r&&t.lexical&&">"==t.lexical.type||(e.eat("=")?"!"!=r&&"="!=r||e.eat("="):/[<>*+\-|&?]/.test(r)&&(e.eat(r),">"==r&&e.eat(r))),"?"==r&&e.eat(".")?p("."):p("operator","operator",e.current());if(u.test(r)){e.eatWhile(u);var i=e.current();if("."!=t.lastType){if(f.propertyIsEnumerable(i)){var o=f[i];return p(o.type,o.style,i)}if("async"==i&&e.match(/^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/,!1))return p("async","keyword",i)}return p("variable","variable",i)}}function g(e,t){for(var n,r=!1;n=e.next();){if("/"==n&&r){t.tokenize=m;break}r="*"==n}return p("comment","comment")}function v(e,t){for(var n,r=!1;null!=(n=e.next());){if(!r&&("`"==n||"$"==n&&e.eat("{"))){t.tokenize=m;break}r=!r&&"\\"==n}return p("quasi","string-2",e.current())}function y(e,t){t.fatArrowAt&&(t.fatArrowAt=null);var n=e.string.indexOf("=>",e.start);if(!(n<0)){if(c){var r=/:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(e.string.slice(e.start,n));r&&(n=r.index)}for(var i=0,o=!1,a=n-1;a>=0;--a){var l=e.string.charAt(a),s="([{}])".indexOf(l);if(s>=0&&s<3){if(!i){++a;break}if(0==--i){"("==l&&(o=!0);break}}else if(s>=3&&s<6)++i;else if(u.test(l))o=!0;else if(/["'\/`]/.test(l))for(;;--a){if(0==a)return;if(e.string.charAt(a-1)==l&&"\\"!=e.string.charAt(a-2)){a--;break}}else if(o&&!i){++a;break}}o&&!i&&(t.fatArrowAt=a)}}var b={atom:!0,number:!0,variable:!0,string:!0,regexp:!0,this:!0,"jsonld-keyword":!0};function x(e,t,n,r,i,o){this.indented=e,this.column=t,this.type=n,this.prev=i,this.info=o,null!=r&&(this.align=r)}function w(e,t){for(var n=e.localVars;n;n=n.next)if(n.name==t)return!0;for(var r=e.context;r;r=r.prev)for(n=r.vars;n;n=n.next)if(n.name==t)return!0}var k={state:null,column:null,marked:null,cc:null};function C(){for(var e=arguments.length-1;e>=0;e--)k.cc.push(arguments[e])}function S(){return C.apply(null,arguments),!0}function T(e,t){for(var n=t;n;n=n.next)if(n.name==e)return!0;return!1}function L(e){var t=k.state;if(k.marked="def",t.context)if("var"==t.lexical.info&&t.context&&t.context.block){var r=function e(t,n){if(n){if(n.block){var r=e(t,n.prev);return r?r==n.prev?n:new O(r,n.vars,!0):null}return T(t,n.vars)?n:new O(n.prev,new N(t,n.vars),!1)}return null}(e,t.context);if(null!=r)return void(t.context=r)}else if(!T(e,t.localVars))return void(t.localVars=new N(e,t.localVars));n.globalVars&&!T(e,t.globalVars)&&(t.globalVars=new N(e,t.globalVars))}function M(e){return"public"==e||"private"==e||"protected"==e||"abstract"==e||"readonly"==e}function O(e,t,n){this.prev=e,this.vars=t,this.block=n}function N(e,t){this.name=e,this.next=t}var A=new N("this",new N("arguments",null));function E(){k.state.context=new O(k.state.context,k.state.localVars,!1),k.state.localVars=A}function z(){k.state.context=new O(k.state.context,k.state.localVars,!0),k.state.localVars=null}function P(){k.state.localVars=k.state.context.vars,k.state.context=k.state.context.prev}function D(e,t){var n=function(){var n=k.state,r=n.indented;if("stat"==n.lexical.type)r=n.lexical.indented;else for(var i=n.lexical;i&&")"==i.type&&i.align;i=i.prev)r=i.indented;n.lexical=new x(r,k.stream.column(),e,null,n.lexical,t)};return n.lex=!0,n}function I(){var e=k.state;e.lexical.prev&&(")"==e.lexical.type&&(e.indented=e.lexical.indented),e.lexical=e.lexical.prev)}function F(e){return function t(n){return n==e?S():";"==e||"}"==n||")"==n||"]"==n?C():S(t)}}function _(e,t){return"var"==e?S(D("vardef",t),ye,F(";"),I):"keyword a"==e?S(D("form"),B,_,I):"keyword b"==e?S(D("form"),_,I):"keyword d"==e?k.stream.match(/^\s*$/,!1)?S():S(D("stat"),q,F(";"),I):"debugger"==e?S(F(";")):"{"==e?S(D("}"),z,oe,I,P):";"==e?S():"if"==e?("else"==k.state.lexical.info&&k.state.cc[k.state.cc.length-1]==I&&k.state.cc.pop()(),S(D("form"),B,_,I,Se)):"function"==e?S(Oe):"for"==e?S(D("form"),Te,_,I):"class"==e||c&&"interface"==t?(k.marked="keyword",S(D("form","class"==e?e:t),Pe,I)):"variable"==e?c&&"declare"==t?(k.marked="keyword",S(_)):c&&("module"==t||"enum"==t||"type"==t)&&k.stream.match(/^\s*\w/,!1)?(k.marked="keyword","enum"==t?S(Ve):"type"==t?S(Ae,F("operator"),ue,F(";")):S(D("form"),be,F("{"),D("}"),oe,I,I)):c&&"namespace"==t?(k.marked="keyword",S(D("form"),H,_,I)):c&&"abstract"==t?(k.marked="keyword",S(_)):S(D("stat"),Q):"switch"==e?S(D("form"),B,F("{"),D("}","switch"),z,oe,I,I,P):"case"==e?S(H,F(":")):"default"==e?S(F(":")):"catch"==e?S(D("form"),E,W,_,I,P):"export"==e?S(D("stat"),_e,I):"import"==e?S(D("stat"),He,I):"async"==e?S(_):"@"==t?S(H,_):C(D("stat"),H,F(";"),I)}function W(e){if("("==e)return S(Ee,F(")"))}function H(e,t){return j(e,t,!1)}function R(e,t){return j(e,t,!0)}function B(e){return"("!=e?C():S(D(")"),q,F(")"),I)}function j(e,t,n){if(k.state.fatArrowAt==k.stream.start){var r=n?X:G;if("("==e)return S(E,D(")"),re(Ee,")"),I,F("=>"),r,P);if("variable"==e)return C(E,be,F("=>"),r,P)}var i=n?V:U;return b.hasOwnProperty(e)?S(i):"function"==e?S(Oe,i):"class"==e||c&&"interface"==t?(k.marked="keyword",S(D("form"),ze,I)):"keyword c"==e||"async"==e?S(n?R:H):"("==e?S(D(")"),q,F(")"),I,i):"operator"==e||"spread"==e?S(n?R:H):"["==e?S(D("]"),Ue,I,i):"{"==e?ie(ee,"}",null,i):"quasi"==e?C(K,i):"new"==e?S(function(e){return function(t){return"."==t?S(e?Y:Z):"variable"==t&&c?S(me,e?V:U):C(e?R:H)}}(n)):"import"==e?S(H):S()}function q(e){return e.match(/[;\}\)\],]/)?C():C(H)}function U(e,t){return","==e?S(q):V(e,t,!1)}function V(e,t,n){var r=0==n?U:V,i=0==n?H:R;return"=>"==e?S(E,n?X:G,P):"operator"==e?/\+\+|--/.test(t)||c&&"!"==t?S(r):c&&"<"==t&&k.stream.match(/^([^<>]|<[^<>]*>)*>\s*\(/,!1)?S(D(">"),re(ue,">"),I,r):"?"==t?S(H,F(":"),i):S(i):"quasi"==e?C(K,r):";"!=e?"("==e?ie(R,")","call",r):"."==e?S(J,r):"["==e?S(D("]"),q,F("]"),I,r):c&&"as"==t?(k.marked="keyword",S(ue,r)):"regexp"==e?(k.state.lastType=k.marked="operator",k.stream.backUp(k.stream.pos-k.stream.start-1),S(i)):void 0:void 0}function K(e,t){return"quasi"!=e?C():"${"!=t.slice(t.length-2)?S(K):S(H,$)}function $(e){if("}"==e)return k.marked="string-2",k.state.tokenize=v,S(K)}function G(e){return y(k.stream,k.state),C("{"==e?_:H)}function X(e){return y(k.stream,k.state),C("{"==e?_:R)}function Z(e,t){if("target"==t)return k.marked="keyword",S(U)}function Y(e,t){if("target"==t)return k.marked="keyword",S(V)}function Q(e){return":"==e?S(I,_):C(U,F(";"),I)}function J(e){if("variable"==e)return k.marked="property",S()}function ee(e,t){return"async"==e?(k.marked="property",S(ee)):"variable"==e||"keyword"==k.style?(k.marked="property","get"==t||"set"==t?S(te):(c&&k.state.fatArrowAt==k.stream.start&&(n=k.stream.match(/^\s*:\s*/,!1))&&(k.state.fatArrowAt=k.stream.pos+n[0].length),S(ne))):"number"==e||"string"==e?(k.marked=l?"property":k.style+" property",S(ne)):"jsonld-keyword"==e?S(ne):c&&M(t)?(k.marked="keyword",S(ee)):"["==e?S(H,ae,F("]"),ne):"spread"==e?S(R,ne):"*"==t?(k.marked="keyword",S(ee)):":"==e?C(ne):void 0;var n}function te(e){return"variable"!=e?C(ne):(k.marked="property",S(Oe))}function ne(e){return":"==e?S(R):"("==e?C(Oe):void 0}function re(e,t,n){function r(i,o){if(n?n.indexOf(i)>-1:","==i){var a=k.state.lexical;return"call"==a.info&&(a.pos=(a.pos||0)+1),S((function(n,r){return n==t||r==t?C():C(e)}),r)}return i==t||o==t?S():n&&n.indexOf(";")>-1?C(e):S(F(t))}return function(n,i){return n==t||i==t?S():C(e,r)}}function ie(e,t,n){for(var r=3;r<arguments.length;r++)k.cc.push(arguments[r]);return S(D(t,n),re(e,t),I)}function oe(e){return"}"==e?S():C(_,oe)}function ae(e,t){if(c){if(":"==e)return S(ue);if("?"==t)return S(ae)}}function le(e,t){if(c&&(":"==e||"in"==t))return S(ue)}function se(e){if(c&&":"==e)return k.stream.match(/^\s*\w+\s+is\b/,!1)?S(H,ce,ue):S(ue)}function ce(e,t){if("is"==t)return k.marked="keyword",S()}function ue(e,t){return"keyof"==t||"typeof"==t||"infer"==t?(k.marked="keyword",S("typeof"==t?R:ue)):"variable"==e||"void"==t?(k.marked="type",S(pe)):"|"==t||"&"==t?S(ue):"string"==e||"number"==e||"atom"==e?S(pe):"["==e?S(D("]"),re(ue,"]",","),I,pe):"{"==e?S(D("}"),re(de,"}",",;"),I,pe):"("==e?S(re(he,")"),fe,pe):"<"==e?S(re(ue,">"),ue):void 0}function fe(e){if("=>"==e)return S(ue)}function de(e,t){return"variable"==e||"keyword"==k.style?(k.marked="property",S(de)):"?"==t||"number"==e||"string"==e?S(de):":"==e?S(ue):"["==e?S(F("variable"),le,F("]"),de):"("==e?C(Ne,de):void 0}function he(e,t){return"variable"==e&&k.stream.match(/^\s*[?:]/,!1)||"?"==t?S(he):":"==e?S(ue):"spread"==e?S(he):C(ue)}function pe(e,t){return"<"==t?S(D(">"),re(ue,">"),I,pe):"|"==t||"."==e||"&"==t?S(ue):"["==e?S(ue,F("]"),pe):"extends"==t||"implements"==t?(k.marked="keyword",S(ue)):"?"==t?S(ue,F(":"),ue):void 0}function me(e,t){if("<"==t)return S(D(">"),re(ue,">"),I,pe)}function ge(){return C(ue,ve)}function ve(e,t){if("="==t)return S(ue)}function ye(e,t){return"enum"==t?(k.marked="keyword",S(Ve)):C(be,ae,ke,Ce)}function be(e,t){return c&&M(t)?(k.marked="keyword",S(be)):"variable"==e?(L(t),S()):"spread"==e?S(be):"["==e?ie(we,"]"):"{"==e?ie(xe,"}"):void 0}function xe(e,t){return"variable"!=e||k.stream.match(/^\s*:/,!1)?("variable"==e&&(k.marked="property"),"spread"==e?S(be):"}"==e?C():"["==e?S(H,F("]"),F(":"),xe):S(F(":"),be,ke)):(L(t),S(ke))}function we(){return C(be,ke)}function ke(e,t){if("="==t)return S(R)}function Ce(e){if(","==e)return S(ye)}function Se(e,t){if("keyword b"==e&&"else"==t)return S(D("form","else"),_,I)}function Te(e,t){return"await"==t?S(Te):"("==e?S(D(")"),Le,I):void 0}function Le(e){return"var"==e?S(ye,Me):"variable"==e?S(Me):C(Me)}function Me(e,t){return")"==e?S():";"==e?S(Me):"in"==t||"of"==t?(k.marked="keyword",S(H,Me)):C(H,Me)}function Oe(e,t){return"*"==t?(k.marked="keyword",S(Oe)):"variable"==e?(L(t),S(Oe)):"("==e?S(E,D(")"),re(Ee,")"),I,se,_,P):c&&"<"==t?S(D(">"),re(ge,">"),I,Oe):void 0}function Ne(e,t){return"*"==t?(k.marked="keyword",S(Ne)):"variable"==e?(L(t),S(Ne)):"("==e?S(E,D(")"),re(Ee,")"),I,se,P):c&&"<"==t?S(D(">"),re(ge,">"),I,Ne):void 0}function Ae(e,t){return"keyword"==e||"variable"==e?(k.marked="type",S(Ae)):"<"==t?S(D(">"),re(ge,">"),I):void 0}function Ee(e,t){return"@"==t&&S(H,Ee),"spread"==e?S(Ee):c&&M(t)?(k.marked="keyword",S(Ee)):c&&"this"==e?S(ae,ke):C(be,ae,ke)}function ze(e,t){return"variable"==e?Pe(e,t):De(e,t)}function Pe(e,t){if("variable"==e)return L(t),S(De)}function De(e,t){return"<"==t?S(D(">"),re(ge,">"),I,De):"extends"==t||"implements"==t||c&&","==e?("implements"==t&&(k.marked="keyword"),S(c?ue:H,De)):"{"==e?S(D("}"),Ie,I):void 0}function Ie(e,t){return"async"==e||"variable"==e&&("static"==t||"get"==t||"set"==t||c&&M(t))&&k.stream.match(/^\s+[\w$\xa1-\uffff]/,!1)?(k.marked="keyword",S(Ie)):"variable"==e||"keyword"==k.style?(k.marked="property",S(Fe,Ie)):"number"==e||"string"==e?S(Fe,Ie):"["==e?S(H,ae,F("]"),Fe,Ie):"*"==t?(k.marked="keyword",S(Ie)):c&&"("==e?C(Ne,Ie):";"==e||","==e?S(Ie):"}"==e?S():"@"==t?S(H,Ie):void 0}function Fe(e,t){if("?"==t)return S(Fe);if(":"==e)return S(ue,ke);if("="==t)return S(R);var n=k.state.lexical.prev;return C(n&&"interface"==n.info?Ne:Oe)}function _e(e,t){return"*"==t?(k.marked="keyword",S(qe,F(";"))):"default"==t?(k.marked="keyword",S(H,F(";"))):"{"==e?S(re(We,"}"),qe,F(";")):C(_)}function We(e,t){return"as"==t?(k.marked="keyword",S(F("variable"))):"variable"==e?C(R,We):void 0}function He(e){return"string"==e?S():"("==e?C(H):C(Re,Be,qe)}function Re(e,t){return"{"==e?ie(Re,"}"):("variable"==e&&L(t),"*"==t&&(k.marked="keyword"),S(je))}function Be(e){if(","==e)return S(Re,Be)}function je(e,t){if("as"==t)return k.marked="keyword",S(Re)}function qe(e,t){if("from"==t)return k.marked="keyword",S(H)}function Ue(e){return"]"==e?S():C(re(R,"]"))}function Ve(){return C(D("form"),be,F("{"),D("}"),re(Ke,"}"),I,I)}function Ke(){return C(be,ke)}function $e(e,t,n){return t.tokenize==m&&/^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(t.lastType)||"quasi"==t.lastType&&/\{\s*$/.test(e.string.slice(0,e.pos-(n||0)))}return P.lex=!0,I.lex=!0,{startState:function(e){var t={tokenize:m,lastType:"sof",cc:[],lexical:new x((e||0)-o,0,"block",!1),localVars:n.localVars,context:n.localVars&&new O(null,null,!1),indented:e||0};return n.globalVars&&"object"==typeof n.globalVars&&(t.globalVars=n.globalVars),t},token:function(e,t){if(e.sol()&&(t.lexical.hasOwnProperty("align")||(t.lexical.align=!1),t.indented=e.indentation(),y(e,t)),t.tokenize!=g&&e.eatSpace())return null;var n=t.tokenize(e,t);return"comment"==r?n:(t.lastType="operator"!=r||"++"!=i&&"--"!=i?r:"incdec",function(e,t,n,r,i){var o=e.cc;for(k.state=e,k.stream=i,k.marked=null,k.cc=o,k.style=t,e.lexical.hasOwnProperty("align")||(e.lexical.align=!0);;)if((o.length?o.pop():s?H:_)(n,r)){for(;o.length&&o[o.length-1].lex;)o.pop()();return k.marked?k.marked:"variable"==n&&w(e,r)?"variable-2":t}}(t,n,r,i,e))},indent:function(t,r){if(t.tokenize==g||t.tokenize==v)return e.Pass;if(t.tokenize!=m)return 0;var i,l=r&&r.charAt(0),s=t.lexical;if(!/^\s*else\b/.test(r))for(var c=t.cc.length-1;c>=0;--c){var u=t.cc[c];if(u==I)s=s.prev;else if(u!=Se)break}for(;("stat"==s.type||"form"==s.type)&&("}"==l||(i=t.cc[t.cc.length-1])&&(i==U||i==V)&&!/^[,\.=+\-*:?[\(]/.test(r));)s=s.prev;a&&")"==s.type&&"stat"==s.prev.type&&(s=s.prev);var f=s.type,h=l==f;return"vardef"==f?s.indented+("operator"==t.lastType||","==t.lastType?s.info.length+1:0):"form"==f&&"{"==l?s.indented:"form"==f?s.indented+o:"stat"==f?s.indented+(function(e,t){return"operator"==e.lastType||","==e.lastType||d.test(t.charAt(0))||/[,.]/.test(t.charAt(0))}(t,r)?a||o:0):"switch"!=s.info||h||0==n.doubleIndentSwitch?s.align?s.column+(h?0:1):s.indented+(h?0:o):s.indented+(/^(?:case|default)\b/.test(r)?o:2*o)},electricInput:/^\s*(?:case .*?:|default:|\{|\})$/,blockCommentStart:s?null:"/*",blockCommentEnd:s?null:"*/",blockCommentContinue:s?null:" * ",lineComment:s?null:"//",fold:"brace",closeBrackets:"()[]{}''\"\"``",helperType:s?"json":"javascript",jsonldMode:l,jsonMode:s,expressionAllowed:$e,skipExpression:function(e){var t=e.cc[e.cc.length-1];t!=H&&t!=R||e.cc.pop()}}})),e.registerHelper("wordChars","javascript",/[\w$]/),e.defineMIME("text/javascript","javascript"),e.defineMIME("text/ecmascript","javascript"),e.defineMIME("application/javascript","javascript"),e.defineMIME("application/x-javascript","javascript"),e.defineMIME("application/ecmascript","javascript"),e.defineMIME("application/json",{name:"javascript",json:!0}),e.defineMIME("application/x-json",{name:"javascript",json:!0}),e.defineMIME("application/ld+json",{name:"javascript",jsonld:!0}),e.defineMIME("text/typescript",{name:"javascript",typescript:!0}),e.defineMIME("application/typescript",{name:"javascript",typescript:!0})}(n(0))},function(e,t,n){!function(e){"use strict";var t={autoSelfClosers:{area:!0,base:!0,br:!0,col:!0,command:!0,embed:!0,frame:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0,menuitem:!0},implicitlyClosed:{dd:!0,li:!0,optgroup:!0,option:!0,p:!0,rp:!0,rt:!0,tbody:!0,td:!0,tfoot:!0,th:!0,tr:!0},contextGrabbers:{dd:{dd:!0,dt:!0},dt:{dd:!0,dt:!0},li:{li:!0},option:{option:!0,optgroup:!0},optgroup:{optgroup:!0},p:{address:!0,article:!0,aside:!0,blockquote:!0,dir:!0,div:!0,dl:!0,fieldset:!0,footer:!0,form:!0,h1:!0,h2:!0,h3:!0,h4:!0,h5:!0,h6:!0,header:!0,hgroup:!0,hr:!0,menu:!0,nav:!0,ol:!0,p:!0,pre:!0,section:!0,table:!0,ul:!0},rp:{rp:!0,rt:!0},rt:{rp:!0,rt:!0},tbody:{tbody:!0,tfoot:!0},td:{td:!0,th:!0},tfoot:{tbody:!0},th:{td:!0,th:!0},thead:{tbody:!0,tfoot:!0},tr:{tr:!0}},doNotIndent:{pre:!0},allowUnquoted:!0,allowMissing:!0,caseFold:!0},n={autoSelfClosers:{},implicitlyClosed:{},contextGrabbers:{},doNotIndent:{},allowUnquoted:!1,allowMissing:!1,allowMissingTagName:!1,caseFold:!1};e.defineMode("xml",(function(r,i){var o,a,l=r.indentUnit,s={},c=i.htmlMode?t:n;for(var u in c)s[u]=c[u];for(var u in i)s[u]=i[u];function f(e,t){function n(n){return t.tokenize=n,n(e,t)}var r=e.next();return"<"==r?e.eat("!")?e.eat("[")?e.match("CDATA[")?n(h("atom","]]>")):null:e.match("--")?n(h("comment","--\x3e")):e.match("DOCTYPE",!0,!0)?(e.eatWhile(/[\w\._\-]/),n(function e(t){return function(n,r){for(var i;null!=(i=n.next());){if("<"==i)return r.tokenize=e(t+1),r.tokenize(n,r);if(">"==i){if(1==t){r.tokenize=f;break}return r.tokenize=e(t-1),r.tokenize(n,r)}}return"meta"}}(1))):null:e.eat("?")?(e.eatWhile(/[\w\._\-]/),t.tokenize=h("meta","?>"),"meta"):(o=e.eat("/")?"closeTag":"openTag",t.tokenize=d,"tag bracket"):"&"==r?(e.eat("#")?e.eat("x")?e.eatWhile(/[a-fA-F\d]/)&&e.eat(";"):e.eatWhile(/[\d]/)&&e.eat(";"):e.eatWhile(/[\w\.\-:]/)&&e.eat(";"))?"atom":"error":(e.eatWhile(/[^&<]/),null)}function d(e,t){var n,r,i=e.next();if(">"==i||"/"==i&&e.eat(">"))return t.tokenize=f,o=">"==i?"endTag":"selfcloseTag","tag bracket";if("="==i)return o="equals",null;if("<"==i){t.tokenize=f,t.state=v,t.tagName=t.tagStart=null;var a=t.tokenize(e,t);return a?a+" tag error":"tag error"}return/[\'\"]/.test(i)?(t.tokenize=(n=i,(r=function(e,t){for(;!e.eol();)if(e.next()==n){t.tokenize=d;break}return"string"}).isInAttribute=!0,r),t.stringStartCol=e.column(),t.tokenize(e,t)):(e.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/),"word")}function h(e,t){return function(n,r){for(;!n.eol();){if(n.match(t)){r.tokenize=f;break}n.next()}return e}}function p(e,t,n){this.prev=e.context,this.tagName=t,this.indent=e.indented,this.startOfLine=n,(s.doNotIndent.hasOwnProperty(t)||e.context&&e.context.noIndent)&&(this.noIndent=!0)}function m(e){e.context&&(e.context=e.context.prev)}function g(e,t){for(var n;;){if(!e.context)return;if(n=e.context.tagName,!s.contextGrabbers.hasOwnProperty(n)||!s.contextGrabbers[n].hasOwnProperty(t))return;m(e)}}function v(e,t,n){return"openTag"==e?(n.tagStart=t.column(),y):"closeTag"==e?b:v}function y(e,t,n){return"word"==e?(n.tagName=t.current(),a="tag",k):s.allowMissingTagName&&"endTag"==e?(a="tag bracket",k(e,0,n)):(a="error",y)}function b(e,t,n){if("word"==e){var r=t.current();return n.context&&n.context.tagName!=r&&s.implicitlyClosed.hasOwnProperty(n.context.tagName)&&m(n),n.context&&n.context.tagName==r||!1===s.matchClosing?(a="tag",x):(a="tag error",w)}return s.allowMissingTagName&&"endTag"==e?(a="tag bracket",x(e,0,n)):(a="error",w)}function x(e,t,n){return"endTag"!=e?(a="error",x):(m(n),v)}function w(e,t,n){return a="error",x(e,0,n)}function k(e,t,n){if("word"==e)return a="attribute",C;if("endTag"==e||"selfcloseTag"==e){var r=n.tagName,i=n.tagStart;return n.tagName=n.tagStart=null,"selfcloseTag"==e||s.autoSelfClosers.hasOwnProperty(r)?g(n,r):(g(n,r),n.context=new p(n,r,i==n.indented)),v}return a="error",k}function C(e,t,n){return"equals"==e?S:(s.allowMissing||(a="error"),k(e,0,n))}function S(e,t,n){return"string"==e?T:"word"==e&&s.allowUnquoted?(a="string",k):(a="error",k(e,0,n))}function T(e,t,n){return"string"==e?T:k(e,0,n)}return f.isInText=!0,{startState:function(e){var t={tokenize:f,state:v,indented:e||0,tagName:null,tagStart:null,context:null};return null!=e&&(t.baseIndent=e),t},token:function(e,t){if(!t.tagName&&e.sol()&&(t.indented=e.indentation()),e.eatSpace())return null;o=null;var n=t.tokenize(e,t);return(n||o)&&"comment"!=n&&(a=null,t.state=t.state(o||n,e,t),a&&(n="error"==a?n+" error":a)),n},indent:function(t,n,r){var i=t.context;if(t.tokenize.isInAttribute)return t.tagStart==t.indented?t.stringStartCol+1:t.indented+l;if(i&&i.noIndent)return e.Pass;if(t.tokenize!=d&&t.tokenize!=f)return r?r.match(/^(\s*)/)[0].length:0;if(t.tagName)return!1!==s.multilineTagIndentPastTag?t.tagStart+t.tagName.length+2:t.tagStart+l*(s.multilineTagIndentFactor||1);if(s.alignCDATA&&/<!\[CDATA\[/.test(n))return 0;var o=n&&/^<(\/)?([\w_:\.-]*)/.exec(n);if(o&&o[1])for(;i;){if(i.tagName==o[2]){i=i.prev;break}if(!s.implicitlyClosed.hasOwnProperty(i.tagName))break;i=i.prev}else if(o)for(;i;){var a=s.contextGrabbers[i.tagName];if(!a||!a.hasOwnProperty(o[2]))break;i=i.prev}for(;i&&i.prev&&!i.startOfLine;)i=i.prev;return i?i.indent+l:t.baseIndent||0},electricInput:/<\/[\s\w:]+>$/,blockCommentStart:"\x3c!--",blockCommentEnd:"--\x3e",configuration:s.htmlMode?"html":"xml",helperType:s.htmlMode?"html":"xml",skipAttribute:function(e){e.state==S&&(e.state=k)},xmlCurrentTag:function(e){return e.tagName?{name:e.tagName,close:"closeTag"==e.type}:null},xmlCurrentContext:function(e){for(var t=[],n=e.context;n;n=n.prev)n.tagName&&t.push(n.tagName);return t.reverse()}}})),e.defineMIME("text/xml","xml"),e.defineMIME("application/xml","xml"),e.mimeModes.hasOwnProperty("text/html")||e.defineMIME("text/html",{name:"xml",htmlMode:!0})}(n(0))},function(e,t,n){!function(e){function t(t,n,r){var i,o=t.getWrapperElement();return(i=o.appendChild(document.createElement("div"))).className=r?"CodeMirror-dialog CodeMirror-dialog-bottom":"CodeMirror-dialog CodeMirror-dialog-top","string"==typeof n?i.innerHTML=n:i.appendChild(n),e.addClass(o,"dialog-opened"),i}function n(e,t){e.state.currentNotificationClose&&e.state.currentNotificationClose(),e.state.currentNotificationClose=t}e.defineExtension("openDialog",(function(r,i,o){o||(o={}),n(this,null);var a=t(this,r,o.bottom),l=!1,s=this;function c(t){if("string"==typeof t)f.value=t;else{if(l)return;l=!0,e.rmClass(a.parentNode,"dialog-opened"),a.parentNode.removeChild(a),s.focus(),o.onClose&&o.onClose(a)}}var u,f=a.getElementsByTagName("input")[0];return f?(f.focus(),o.value&&(f.value=o.value,!1!==o.selectValueOnOpen&&f.select()),o.onInput&&e.on(f,"input",(function(e){o.onInput(e,f.value,c)})),o.onKeyUp&&e.on(f,"keyup",(function(e){o.onKeyUp(e,f.value,c)})),e.on(f,"keydown",(function(t){o&&o.onKeyDown&&o.onKeyDown(t,f.value,c)||((27==t.keyCode||!1!==o.closeOnEnter&&13==t.keyCode)&&(f.blur(),e.e_stop(t),c()),13==t.keyCode&&i(f.value,t))})),!1!==o.closeOnBlur&&e.on(f,"blur",c)):(u=a.getElementsByTagName("button")[0])&&(e.on(u,"click",(function(){c(),s.focus()})),!1!==o.closeOnBlur&&e.on(u,"blur",c),u.focus()),c})),e.defineExtension("openConfirm",(function(r,i,o){n(this,null);var a=t(this,r,o&&o.bottom),l=a.getElementsByTagName("button"),s=!1,c=this,u=1;function f(){s||(s=!0,e.rmClass(a.parentNode,"dialog-opened"),a.parentNode.removeChild(a),c.focus())}l[0].focus();for(var d=0;d<l.length;++d){var h=l[d];!function(t){e.on(h,"click",(function(n){e.e_preventDefault(n),f(),t&&t(c)}))}(i[d]),e.on(h,"blur",(function(){--u,setTimeout((function(){u<=0&&f()}),200)})),e.on(h,"focus",(function(){++u}))}})),e.defineExtension("openNotification",(function(r,i){n(this,c);var o,a=t(this,r,i&&i.bottom),l=!1,s=i&&void 0!==i.duration?i.duration:5e3;function c(){l||(l=!0,clearTimeout(o),e.rmClass(a.parentNode,"dialog-opened"),a.parentNode.removeChild(a))}return e.on(a,"click",(function(t){e.e_preventDefault(t),c()})),s&&(o=setTimeout(c,s)),c}))}(n(0))},function(e,t,n){!function(e){"use strict";function t(e){for(var t={},n=0;n<e.length;++n)t[e[n].toLowerCase()]=!0;return t}e.defineMode("css",(function(t,n){var r=n.inline;n.propertyKeywords||(n=e.resolveMode("text/css"));var i,o,a=t.indentUnit,l=n.tokenHooks,s=n.documentTypes||{},c=n.mediaTypes||{},u=n.mediaFeatures||{},f=n.mediaValueKeywords||{},d=n.propertyKeywords||{},h=n.nonStandardPropertyKeywords||{},p=n.fontProperties||{},m=n.counterDescriptors||{},g=n.colorKeywords||{},v=n.valueKeywords||{},y=n.allowNested,b=n.lineComment,x=!0===n.supportsAtComponent;function w(e,t){return i=t,e}function k(e,t){var n=e.next();if(l[n]){var r=l[n](e,t);if(!1!==r)return r}return"@"==n?(e.eatWhile(/[\w\\\-]/),w("def",e.current())):"="==n||("~"==n||"|"==n)&&e.eat("=")?w(null,"compare"):'"'==n||"'"==n?(t.tokenize=C(n),t.tokenize(e,t)):"#"==n?(e.eatWhile(/[\w\\\-]/),w("atom","hash")):"!"==n?(e.match(/^\s*\w*/),w("keyword","important")):/\d/.test(n)||"."==n&&e.eat(/\d/)?(e.eatWhile(/[\w.%]/),w("number","unit")):"-"!==n?/[,+>*\/]/.test(n)?w(null,"select-op"):"."==n&&e.match(/^-?[_a-z][_a-z0-9-]*/i)?w("qualifier","qualifier"):/[:;{}\[\]\(\)]/.test(n)?w(null,n):e.match(/[\w-.]+(?=\()/)?(/^(url(-prefix)?|domain|regexp)$/.test(e.current().toLowerCase())&&(t.tokenize=S),w("variable callee","variable")):/[\w\\\-]/.test(n)?(e.eatWhile(/[\w\\\-]/),w("property","word")):w(null,null):/[\d.]/.test(e.peek())?(e.eatWhile(/[\w.%]/),w("number","unit")):e.match(/^-[\w\\\-]*/)?(e.eatWhile(/[\w\\\-]/),e.match(/^\s*:/,!1)?w("variable-2","variable-definition"):w("variable-2","variable")):e.match(/^\w+-/)?w("meta","meta"):void 0}function C(e){return function(t,n){for(var r,i=!1;null!=(r=t.next());){if(r==e&&!i){")"==e&&t.backUp(1);break}i=!i&&"\\"==r}return(r==e||!i&&")"!=e)&&(n.tokenize=null),w("string","string")}}function S(e,t){return e.next(),e.match(/\s*[\"\')]/,!1)?t.tokenize=null:t.tokenize=C(")"),w(null,"(")}function T(e,t,n){this.type=e,this.indent=t,this.prev=n}function L(e,t,n,r){return e.context=new T(n,t.indentation()+(!1===r?0:a),e.context),n}function M(e){return e.context.prev&&(e.context=e.context.prev),e.context.type}function O(e,t,n){return E[n.context.type](e,t,n)}function N(e,t,n,r){for(var i=r||1;i>0;i--)n.context=n.context.prev;return O(e,t,n)}function A(e){var t=e.current().toLowerCase();o=v.hasOwnProperty(t)?"atom":g.hasOwnProperty(t)?"keyword":"variable"}var E={top:function(e,t,n){if("{"==e)return L(n,t,"block");if("}"==e&&n.context.prev)return M(n);if(x&&/@component/i.test(e))return L(n,t,"atComponentBlock");if(/^@(-moz-)?document$/i.test(e))return L(n,t,"documentTypes");if(/^@(media|supports|(-moz-)?document|import)$/i.test(e))return L(n,t,"atBlock");if(/^@(font-face|counter-style)/i.test(e))return n.stateArg=e,"restricted_atBlock_before";if(/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(e))return"keyframes";if(e&&"@"==e.charAt(0))return L(n,t,"at");if("hash"==e)o="builtin";else if("word"==e)o="tag";else{if("variable-definition"==e)return"maybeprop";if("interpolation"==e)return L(n,t,"interpolation");if(":"==e)return"pseudo";if(y&&"("==e)return L(n,t,"parens")}return n.context.type},block:function(e,t,n){if("word"==e){var r=t.current().toLowerCase();return d.hasOwnProperty(r)?(o="property","maybeprop"):h.hasOwnProperty(r)?(o="string-2","maybeprop"):y?(o=t.match(/^\s*:(?:\s|$)/,!1)?"property":"tag","block"):(o+=" error","maybeprop")}return"meta"==e?"block":y||"hash"!=e&&"qualifier"!=e?E.top(e,t,n):(o="error","block")},maybeprop:function(e,t,n){return":"==e?L(n,t,"prop"):O(e,t,n)},prop:function(e,t,n){if(";"==e)return M(n);if("{"==e&&y)return L(n,t,"propBlock");if("}"==e||"{"==e)return N(e,t,n);if("("==e)return L(n,t,"parens");if("hash"!=e||/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(t.current())){if("word"==e)A(t);else if("interpolation"==e)return L(n,t,"interpolation")}else o+=" error";return"prop"},propBlock:function(e,t,n){return"}"==e?M(n):"word"==e?(o="property","maybeprop"):n.context.type},parens:function(e,t,n){return"{"==e||"}"==e?N(e,t,n):")"==e?M(n):"("==e?L(n,t,"parens"):"interpolation"==e?L(n,t,"interpolation"):("word"==e&&A(t),"parens")},pseudo:function(e,t,n){return"meta"==e?"pseudo":"word"==e?(o="variable-3",n.context.type):O(e,t,n)},documentTypes:function(e,t,n){return"word"==e&&s.hasOwnProperty(t.current())?(o="tag",n.context.type):E.atBlock(e,t,n)},atBlock:function(e,t,n){if("("==e)return L(n,t,"atBlock_parens");if("}"==e||";"==e)return N(e,t,n);if("{"==e)return M(n)&&L(n,t,y?"block":"top");if("interpolation"==e)return L(n,t,"interpolation");if("word"==e){var r=t.current().toLowerCase();o="only"==r||"not"==r||"and"==r||"or"==r?"keyword":c.hasOwnProperty(r)?"attribute":u.hasOwnProperty(r)?"property":f.hasOwnProperty(r)?"keyword":d.hasOwnProperty(r)?"property":h.hasOwnProperty(r)?"string-2":v.hasOwnProperty(r)?"atom":g.hasOwnProperty(r)?"keyword":"error"}return n.context.type},atComponentBlock:function(e,t,n){return"}"==e?N(e,t,n):"{"==e?M(n)&&L(n,t,y?"block":"top",!1):("word"==e&&(o="error"),n.context.type)},atBlock_parens:function(e,t,n){return")"==e?M(n):"{"==e||"}"==e?N(e,t,n,2):E.atBlock(e,t,n)},restricted_atBlock_before:function(e,t,n){return"{"==e?L(n,t,"restricted_atBlock"):"word"==e&&"@counter-style"==n.stateArg?(o="variable","restricted_atBlock_before"):O(e,t,n)},restricted_atBlock:function(e,t,n){return"}"==e?(n.stateArg=null,M(n)):"word"==e?(o="@font-face"==n.stateArg&&!p.hasOwnProperty(t.current().toLowerCase())||"@counter-style"==n.stateArg&&!m.hasOwnProperty(t.current().toLowerCase())?"error":"property","maybeprop"):"restricted_atBlock"},keyframes:function(e,t,n){return"word"==e?(o="variable","keyframes"):"{"==e?L(n,t,"top"):O(e,t,n)},at:function(e,t,n){return";"==e?M(n):"{"==e||"}"==e?N(e,t,n):("word"==e?o="tag":"hash"==e&&(o="builtin"),"at")},interpolation:function(e,t,n){return"}"==e?M(n):"{"==e||";"==e?N(e,t,n):("word"==e?o="variable":"variable"!=e&&"("!=e&&")"!=e&&(o="error"),"interpolation")}};return{startState:function(e){return{tokenize:null,state:r?"block":"top",stateArg:null,context:new T(r?"block":"top",e||0,null)}},token:function(e,t){if(!t.tokenize&&e.eatSpace())return null;var n=(t.tokenize||k)(e,t);return n&&"object"==typeof n&&(i=n[1],n=n[0]),o=n,"comment"!=i&&(t.state=E[t.state](i,e,t)),o},indent:function(e,t){var n=e.context,r=t&&t.charAt(0),i=n.indent;return"prop"!=n.type||"}"!=r&&")"!=r||(n=n.prev),n.prev&&("}"!=r||"block"!=n.type&&"top"!=n.type&&"interpolation"!=n.type&&"restricted_atBlock"!=n.type?(")"!=r||"parens"!=n.type&&"atBlock_parens"!=n.type)&&("{"!=r||"at"!=n.type&&"atBlock"!=n.type)||(i=Math.max(0,n.indent-a)):i=(n=n.prev).indent),i},electricChars:"}",blockCommentStart:"/*",blockCommentEnd:"*/",blockCommentContinue:" * ",lineComment:b,fold:"brace"}}));var n=["domain","regexp","url","url-prefix"],r=t(n),i=["all","aural","braille","handheld","print","projection","screen","tty","tv","embossed"],o=t(i),a=["width","min-width","max-width","height","min-height","max-height","device-width","min-device-width","max-device-width","device-height","min-device-height","max-device-height","aspect-ratio","min-aspect-ratio","max-aspect-ratio","device-aspect-ratio","min-device-aspect-ratio","max-device-aspect-ratio","color","min-color","max-color","color-index","min-color-index","max-color-index","monochrome","min-monochrome","max-monochrome","resolution","min-resolution","max-resolution","scan","grid","orientation","device-pixel-ratio","min-device-pixel-ratio","max-device-pixel-ratio","pointer","any-pointer","hover","any-hover"],l=t(a),s=["landscape","portrait","none","coarse","fine","on-demand","hover","interlace","progressive"],c=t(s),u=["align-content","align-items","align-self","alignment-adjust","alignment-baseline","anchor-point","animation","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-timing-function","appearance","azimuth","backface-visibility","background","background-attachment","background-blend-mode","background-clip","background-color","background-image","background-origin","background-position","background-repeat","background-size","baseline-shift","binding","bleed","bookmark-label","bookmark-level","bookmark-state","bookmark-target","border","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-decoration-break","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","caret-color","clear","clip","color","color-profile","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","content","counter-increment","counter-reset","crop","cue","cue-after","cue-before","cursor","direction","display","dominant-baseline","drop-initial-after-adjust","drop-initial-after-align","drop-initial-before-adjust","drop-initial-before-align","drop-initial-size","drop-initial-value","elevation","empty-cells","fit","fit-position","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","float-offset","flow-from","flow-into","font","font-feature-settings","font-family","font-kerning","font-language-override","font-size","font-size-adjust","font-stretch","font-style","font-synthesis","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-ligatures","font-variant-numeric","font-variant-position","font-weight","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-column","grid-column-end","grid-column-gap","grid-column-start","grid-gap","grid-row","grid-row-end","grid-row-gap","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphens","icon","image-orientation","image-rendering","image-resolution","inline-box-align","justify-content","justify-items","justify-self","left","letter-spacing","line-break","line-height","line-stacking","line-stacking-ruby","line-stacking-shift","line-stacking-strategy","list-style","list-style-image","list-style-position","list-style-type","margin","margin-bottom","margin-left","margin-right","margin-top","marks","marquee-direction","marquee-loop","marquee-play-count","marquee-speed","marquee-style","max-height","max-width","min-height","min-width","mix-blend-mode","move-to","nav-down","nav-index","nav-left","nav-right","nav-up","object-fit","object-position","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-style","overflow-wrap","overflow-x","overflow-y","padding","padding-bottom","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","page-policy","pause","pause-after","pause-before","perspective","perspective-origin","pitch","pitch-range","place-content","place-items","place-self","play-during","position","presentation-level","punctuation-trim","quotes","region-break-after","region-break-before","region-break-inside","region-fragment","rendering-intent","resize","rest","rest-after","rest-before","richness","right","rotation","rotation-point","ruby-align","ruby-overhang","ruby-position","ruby-span","shape-image-threshold","shape-inside","shape-margin","shape-outside","size","speak","speak-as","speak-header","speak-numeral","speak-punctuation","speech-rate","stress","string-set","tab-size","table-layout","target","target-name","target-new","target-position","text-align","text-align-last","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-style","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-height","text-indent","text-justify","text-outline","text-overflow","text-shadow","text-size-adjust","text-space-collapse","text-transform","text-underline-position","text-wrap","top","transform","transform-origin","transform-style","transition","transition-delay","transition-duration","transition-property","transition-timing-function","unicode-bidi","user-select","vertical-align","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","volume","white-space","widows","width","will-change","word-break","word-spacing","word-wrap","z-index","clip-path","clip-rule","mask","enable-background","filter","flood-color","flood-opacity","lighting-color","stop-color","stop-opacity","pointer-events","color-interpolation","color-interpolation-filters","color-rendering","fill","fill-opacity","fill-rule","image-rendering","marker","marker-end","marker-mid","marker-start","shape-rendering","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","text-rendering","baseline-shift","dominant-baseline","glyph-orientation-horizontal","glyph-orientation-vertical","text-anchor","writing-mode"],f=t(u),d=["scrollbar-arrow-color","scrollbar-base-color","scrollbar-dark-shadow-color","scrollbar-face-color","scrollbar-highlight-color","scrollbar-shadow-color","scrollbar-3d-light-color","scrollbar-track-color","shape-inside","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","zoom"],h=t(d),p=t(["font-family","src","unicode-range","font-variant","font-feature-settings","font-stretch","font-weight","font-style"]),m=t(["additive-symbols","fallback","negative","pad","prefix","range","speak-as","suffix","symbols","system"]),g=["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","grey","green","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"],v=t(g),y=["above","absolute","activeborder","additive","activecaption","afar","after-white-space","ahead","alias","all","all-scroll","alphabetic","alternate","always","amharic","amharic-abegede","antialiased","appworkspace","arabic-indic","armenian","asterisks","attr","auto","auto-flow","avoid","avoid-column","avoid-page","avoid-region","background","backwards","baseline","below","bidi-override","binary","bengali","blink","block","block-axis","bold","bolder","border","border-box","both","bottom","break","break-all","break-word","bullets","button","button-bevel","buttonface","buttonhighlight","buttonshadow","buttontext","calc","cambodian","capitalize","caps-lock-indicator","caption","captiontext","caret","cell","center","checkbox","circle","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","clear","clip","close-quote","col-resize","collapse","color","color-burn","color-dodge","column","column-reverse","compact","condensed","contain","content","contents","content-box","context-menu","continuous","copy","counter","counters","cover","crop","cross","crosshair","currentcolor","cursive","cyclic","darken","dashed","decimal","decimal-leading-zero","default","default-button","dense","destination-atop","destination-in","destination-out","destination-over","devanagari","difference","disc","discard","disclosure-closed","disclosure-open","document","dot-dash","dot-dot-dash","dotted","double","down","e-resize","ease","ease-in","ease-in-out","ease-out","element","ellipse","ellipsis","embed","end","ethiopic","ethiopic-abegede","ethiopic-abegede-am-et","ethiopic-abegede-gez","ethiopic-abegede-ti-er","ethiopic-abegede-ti-et","ethiopic-halehame-aa-er","ethiopic-halehame-aa-et","ethiopic-halehame-am-et","ethiopic-halehame-gez","ethiopic-halehame-om-et","ethiopic-halehame-sid-et","ethiopic-halehame-so-et","ethiopic-halehame-ti-er","ethiopic-halehame-ti-et","ethiopic-halehame-tig","ethiopic-numeric","ew-resize","exclusion","expanded","extends","extra-condensed","extra-expanded","fantasy","fast","fill","fixed","flat","flex","flex-end","flex-start","footnotes","forwards","from","geometricPrecision","georgian","graytext","grid","groove","gujarati","gurmukhi","hand","hangul","hangul-consonant","hard-light","hebrew","help","hidden","hide","higher","highlight","highlighttext","hiragana","hiragana-iroha","horizontal","hsl","hsla","hue","hwb","icon","ignore","inactiveborder","inactivecaption","inactivecaptiontext","infinite","infobackground","infotext","inherit","initial","inline","inline-axis","inline-block","inline-flex","inline-grid","inline-table","inset","inside","intrinsic","invert","italic","japanese-formal","japanese-informal","justify","kannada","katakana","katakana-iroha","keep-all","khmer","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","landscape","lao","large","larger","left","level","lighter","lighten","line-through","linear","linear-gradient","lines","list-item","listbox","listitem","local","logical","loud","lower","lower-alpha","lower-armenian","lower-greek","lower-hexadecimal","lower-latin","lower-norwegian","lower-roman","lowercase","ltr","luminosity","malayalam","match","matrix","matrix3d","media-controls-background","media-current-time-display","media-fullscreen-button","media-mute-button","media-play-button","media-return-to-realtime-button","media-rewind-button","media-seek-back-button","media-seek-forward-button","media-slider","media-sliderthumb","media-time-remaining-display","media-volume-slider","media-volume-slider-container","media-volume-sliderthumb","medium","menu","menulist","menulist-button","menulist-text","menulist-textfield","menutext","message-box","middle","min-intrinsic","mix","mongolian","monospace","move","multiple","multiply","myanmar","n-resize","narrower","ne-resize","nesw-resize","no-close-quote","no-drop","no-open-quote","no-repeat","none","normal","not-allowed","nowrap","ns-resize","numbers","numeric","nw-resize","nwse-resize","oblique","octal","opacity","open-quote","optimizeLegibility","optimizeSpeed","oriya","oromo","outset","outside","outside-shape","overlay","overline","padding","padding-box","painted","page","paused","persian","perspective","plus-darker","plus-lighter","pointer","polygon","portrait","pre","pre-line","pre-wrap","preserve-3d","progress","push-button","radial-gradient","radio","read-only","read-write","read-write-plaintext-only","rectangle","region","relative","repeat","repeating-linear-gradient","repeating-radial-gradient","repeat-x","repeat-y","reset","reverse","rgb","rgba","ridge","right","rotate","rotate3d","rotateX","rotateY","rotateZ","round","row","row-resize","row-reverse","rtl","run-in","running","s-resize","sans-serif","saturation","scale","scale3d","scaleX","scaleY","scaleZ","screen","scroll","scrollbar","scroll-position","se-resize","searchfield","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","self-start","self-end","semi-condensed","semi-expanded","separate","serif","show","sidama","simp-chinese-formal","simp-chinese-informal","single","skew","skewX","skewY","skip-white-space","slide","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","slow","small","small-caps","small-caption","smaller","soft-light","solid","somali","source-atop","source-in","source-out","source-over","space","space-around","space-between","space-evenly","spell-out","square","square-button","start","static","status-bar","stretch","stroke","sub","subpixel-antialiased","super","sw-resize","symbolic","symbols","system-ui","table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tamil","telugu","text","text-bottom","text-top","textarea","textfield","thai","thick","thin","threeddarkshadow","threedface","threedhighlight","threedlightshadow","threedshadow","tibetan","tigre","tigrinya-er","tigrinya-er-abegede","tigrinya-et","tigrinya-et-abegede","to","top","trad-chinese-formal","trad-chinese-informal","transform","translate","translate3d","translateX","translateY","translateZ","transparent","ultra-condensed","ultra-expanded","underline","unset","up","upper-alpha","upper-armenian","upper-greek","upper-hexadecimal","upper-latin","upper-norwegian","upper-roman","uppercase","urdu","url","var","vertical","vertical-text","visible","visibleFill","visiblePainted","visibleStroke","visual","w-resize","wait","wave","wider","window","windowframe","windowtext","words","wrap","wrap-reverse","x-large","x-small","xor","xx-large","xx-small"],b=t(y),x=n.concat(i).concat(a).concat(s).concat(u).concat(d).concat(g).concat(y);function w(e,t){for(var n,r=!1;null!=(n=e.next());){if(r&&"/"==n){t.tokenize=null;break}r="*"==n}return["comment","comment"]}e.registerHelper("hintWords","css",x),e.defineMIME("text/css",{documentTypes:r,mediaTypes:o,mediaFeatures:l,mediaValueKeywords:c,propertyKeywords:f,nonStandardPropertyKeywords:h,fontProperties:p,counterDescriptors:m,colorKeywords:v,valueKeywords:b,tokenHooks:{"/":function(e,t){return!!e.eat("*")&&(t.tokenize=w,w(e,t))}},name:"css"}),e.defineMIME("text/x-scss",{mediaTypes:o,mediaFeatures:l,mediaValueKeywords:c,propertyKeywords:f,nonStandardPropertyKeywords:h,colorKeywords:v,valueKeywords:b,fontProperties:p,allowNested:!0,lineComment:"//",tokenHooks:{"/":function(e,t){return e.eat("/")?(e.skipToEnd(),["comment","comment"]):e.eat("*")?(t.tokenize=w,w(e,t)):["operator","operator"]},":":function(e){return!!e.match(/\s*\{/,!1)&&[null,null]},$:function(e){return e.match(/^[\w-]+/),e.match(/^\s*:/,!1)?["variable-2","variable-definition"]:["variable-2","variable"]},"#":function(e){return!!e.eat("{")&&[null,"interpolation"]}},name:"css",helperType:"scss"}),e.defineMIME("text/x-less",{mediaTypes:o,mediaFeatures:l,mediaValueKeywords:c,propertyKeywords:f,nonStandardPropertyKeywords:h,colorKeywords:v,valueKeywords:b,fontProperties:p,allowNested:!0,lineComment:"//",tokenHooks:{"/":function(e,t){return e.eat("/")?(e.skipToEnd(),["comment","comment"]):e.eat("*")?(t.tokenize=w,w(e,t)):["operator","operator"]},"@":function(e){return e.eat("{")?[null,"interpolation"]:!e.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/i,!1)&&(e.eatWhile(/[\w\\\-]/),e.match(/^\s*:/,!1)?["variable-2","variable-definition"]:["variable-2","variable"])},"&":function(){return["atom","atom"]}},name:"css",helperType:"less"}),e.defineMIME("text/x-gss",{documentTypes:r,mediaTypes:o,mediaFeatures:l,propertyKeywords:f,nonStandardPropertyKeywords:h,fontProperties:p,counterDescriptors:m,colorKeywords:v,valueKeywords:b,supportsAtComponent:!0,tokenHooks:{"/":function(e,t){return!!e.eat("*")&&(t.tokenize=w,w(e,t))}},name:"css",helperType:"gss"})}(n(0))},function(e,t,n){!function(e){"use strict";function t(t,n,i,o){if(i&&i.call){var a=i;i=null}else a=r(t,i,"rangeFinder");"number"==typeof n&&(n=e.Pos(n,0));var l=r(t,i,"minFoldSize");function s(e){var r=a(t,n);if(!r||r.to.line-r.from.line<l)return null;for(var i=t.findMarksAt(r.from),s=0;s<i.length;++s)if(i[s].__isFold&&"fold"!==o){if(!e)return null;r.cleared=!0,i[s].clear()}return r}var c=s(!0);if(r(t,i,"scanUp"))for(;!c&&n.line>t.firstLine();)n=e.Pos(n.line-1,0),c=s(!1);if(c&&!c.cleared&&"unfold"!==o){var u=function(e,t){var n=r(e,t,"widget");if("string"==typeof n){var i=document.createTextNode(n);(n=document.createElement("span")).appendChild(i),n.className="CodeMirror-foldmarker"}else n&&(n=n.cloneNode(!0));return n}(t,i);e.on(u,"mousedown",(function(t){f.clear(),e.e_preventDefault(t)}));var f=t.markText(c.from,c.to,{replacedWith:u,clearOnEnter:r(t,i,"clearOnEnter"),__isFold:!0});f.on("clear",(function(n,r){e.signal(t,"unfold",t,n,r)})),e.signal(t,"fold",t,c.from,c.to)}}e.newFoldFunction=function(e,n){return function(r,i){t(r,i,{rangeFinder:e,widget:n})}},e.defineExtension("foldCode",(function(e,n,r){t(this,e,n,r)})),e.defineExtension("isFolded",(function(e){for(var t=this.findMarksAt(e),n=0;n<t.length;++n)if(t[n].__isFold)return!0})),e.commands.toggleFold=function(e){e.foldCode(e.getCursor())},e.commands.fold=function(e){e.foldCode(e.getCursor(),null,"fold")},e.commands.unfold=function(e){e.foldCode(e.getCursor(),null,"unfold")},e.commands.foldAll=function(t){t.operation((function(){for(var n=t.firstLine(),r=t.lastLine();n<=r;n++)t.foldCode(e.Pos(n,0),null,"fold")}))},e.commands.unfoldAll=function(t){t.operation((function(){for(var n=t.firstLine(),r=t.lastLine();n<=r;n++)t.foldCode(e.Pos(n,0),null,"unfold")}))},e.registerHelper("fold","combine",(function(){var e=Array.prototype.slice.call(arguments,0);return function(t,n){for(var r=0;r<e.length;++r){var i=e[r](t,n);if(i)return i}}})),e.registerHelper("fold","auto",(function(e,t){for(var n=e.getHelpers(t,"fold"),r=0;r<n.length;r++){var i=n[r](e,t);if(i)return i}}));var n={rangeFinder:e.fold.auto,widget:"↔",minFoldSize:0,scanUp:!1,clearOnEnter:!0};function r(e,t,r){if(t&&void 0!==t[r])return t[r];var i=e.options.foldOptions;return i&&void 0!==i[r]?i[r]:n[r]}e.defineOption("foldOptions",null),e.defineExtension("foldOption",(function(e,t){return r(this,e,t)}))}(n(0))},function(e,t,n){n(4),n(1),n(8),n(9),n(12),n(13),n(14),n(15),n(2),n(3),n(5),n(16),n(17),n(18),n(19),n(20),n(21),n(22),n(23),n(24),n(26),n(27),n(28),n(6),n(29),n(30),n(31),n(32),n(33),n(34),e.exports=n(0)},function(e,t,n){!function(e){"use strict";function t(){this.posFrom=this.posTo=this.lastQuery=this.query=null,this.overlay=null}function n(e){return e.state.search||(e.state.search=new t)}function r(e){return"string"==typeof e&&e==e.toLowerCase()}function i(e,t,n){return e.getSearchCursor(t,n,{caseFold:r(t),multiline:!0})}function o(e,t,n,r,i){e.openDialog?e.openDialog(t,i,{value:r,selectValueOnOpen:!0}):i(prompt(n,r))}function a(e){return e.replace(/\\([nrt\\])/g,(function(e,t){return"n"==t?"\n":"r"==t?"\r":"t"==t?"\t":"\\"==t?"\\":e}))}function l(e){var t=e.match(/^\/(.*)\/([a-z]*)$/);if(t)try{e=new RegExp(t[1],-1==t[2].indexOf("i")?"":"i")}catch(e){}else e=a(e);return("string"==typeof e?""==e:e.test(""))&&(e=/x^/),e}var s;function c(e,t,n){t.queryText=n,t.query=l(n),e.removeOverlay(t.overlay,r(t.query)),t.overlay=function(e,t){return"string"==typeof e?e=new RegExp(e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&"),t?"gi":"g"):e.global||(e=new RegExp(e.source,e.ignoreCase?"gi":"g")),{token:function(t){e.lastIndex=t.pos;var n=e.exec(t.string);if(n&&n.index==t.pos)return t.pos+=n[0].length||1,"searching";n?t.pos=n.index:t.skipToEnd()}}}(t.query,r(t.query)),e.addOverlay(t.overlay),e.showMatchesOnScrollbar&&(t.annotate&&(t.annotate.clear(),t.annotate=null),t.annotate=e.showMatchesOnScrollbar(t.query,r(t.query)))}function u(t,r,i,a){if(!s){let e=t.getWrapperElement().ownerDocument,n=e.createElement("input");n.type="search",n.placeholder=t.l10n("findCmd.promptMessage"),n.style.marginInlineStart="1em",n.style.marginInlineEnd="1em",n.style.flexGrow="1",n.addEventListener("focus",()=>n.select()),(s=e.createElement("div")).appendChild(n),s.style.display="flex"}var l=n(t);if(l.query)return f(t,r);var u=t.getSelection()||l.lastQuery;if(u instanceof RegExp&&"x^"==u.source&&(u=null),i&&t.openDialog){var h=null,p=function(n,r){e.e_stop(r),n&&(n!=l.queryText&&(c(t,l,n),l.posFrom=l.posTo=t.getCursor()),h&&(h.style.opacity=1),f(t,r.shiftKey,(function(e,n){var r;n.line<3&&document.querySelector&&(r=t.display.wrapper.querySelector(".CodeMirror-dialog"))&&r.getBoundingClientRect().bottom-4>t.cursorCoords(n,"window").top&&((h=r).style.opacity=.4)})))};!function(e,t,n,r,i){e.openDialog(t,r,{value:n,selectValueOnOpen:!0,closeOnEnter:!1,onClose:function(){d(e)},onKeyDown:i})}(t,s,u,p,(function(r,i){var o=e.keyName(r),a=t.getOption("extraKeys"),l=a&&a[o]||e.keyMap[t.getOption("keyMap")][o];"findNext"==l||"findPrev"==l||"findPersistentNext"==l||"findPersistentPrev"==l?(e.e_stop(r),c(t,n(t),i),t.execCommand(l)):"find"!=l&&"findPersistent"!=l||(e.e_stop(r),p(i,r))})),a&&u&&(c(t,l,u),f(t,r))}else o(t,s,"Search for:",u,(function(e){e&&!l.query&&t.operation((function(){c(t,l,e),l.posFrom=l.posTo=t.getCursor(),f(t,r)}))}))}function f(t,r,o){t.operation((function(){var a=n(t),l=i(t,a.query,r?a.posFrom:a.posTo);(l.find(r)||(l=i(t,a.query,r?e.Pos(t.lastLine()):e.Pos(t.firstLine(),0))).find(r))&&(t.setSelection(l.from(),l.to()),t.scrollIntoView({from:l.from(),to:l.to()},20),a.posFrom=l.from(),a.posTo=l.to(),o&&o(l.from(),l.to()))}))}function d(e){e.operation((function(){var t=n(e);t.lastQuery=t.query,t.query&&(t.query=t.queryText=null,e.removeOverlay(t.overlay),t.annotate&&(t.annotate.clear(),t.annotate=null))}))}function h(e,t,n){e.operation((function(){for(var r=i(e,t);r.findNext();)if("string"!=typeof t){var o=e.getRange(r.from(),r.to()).match(t);r.replace(n.replace(/\$(\d)/g,(function(e,t){return o[t]})))}else r.replace(n)}))}function p(e,t){if(e.getOption("readOnly"))return;var r=e.getSelection()||n(e).lastQuery;let s=e.getWrapperElement().ownerDocument,c=s.createElement("span");c.classList.add("CodeMirror-search-label"),c.textContent=t?"Replace all:":"Replace:";let u=s.createDocumentFragment();u.appendChild(c.cloneNode(!0));let f=s.createElement("input");f.setAttribute("type","text"),f.setAttribute("style","width: 10em"),f.classList.add("CodeMirror-search-field"),u.appendChild(f);let p=s.createElement("span");p.setAttribute("style","color: #888"),p.classList.add("CodeMirror-search-hint"),p.textContent="(Use /re/ syntax for regexp search)",u.appendChild(p),o(e,u,c,r,(function(n){if(!n)return;n=l(n);let r=s.createDocumentFragment(),u=c.cloneNode(!1);u.textContent="With:",r.appendChild(u);let f=s.createElement("input");f.setAttribute("type","text"),f.setAttribute("style","width: 10em"),f.classList.add("CodeMirror-search-field"),r.appendChild(f),o(e,r,"Replace with:","",(function(r){if(r=a(r),t)h(e,n,r);else{d(e);var o=i(e,n,e.getCursor("from")),l=function(){var t,a=o.from();if(!(t=o.findNext())&&(o=i(e,n),!(t=o.findNext())||a&&o.from().line==a.line&&o.from().ch==a.ch))return;e.setSelection(o.from(),o.to()),e.scrollIntoView({from:o.from(),to:o.to()});let f=s.createDocumentFragment(),d=c.cloneNode(!1);d.textContent="Replace?",f.appendChild(d);let p=s.createElement("button");p.textContent="Yes",f.appendChild(p);let m=s.createElement("button");m.textContent="No",f.appendChild(m);let g=s.createElement("button");g.textContent="All",f.appendChild(g);let v=s.createElement("button");v.textContent="Stop",f.appendChild(v),function(e,t,n,r){e.openConfirm?e.openConfirm(t,r):confirm(n)&&r[0]()}(e,f,"Replace?",[function(){u(t)},l,function(){h(e,n,r)}])},u=function(e){o.replace("string"==typeof n?r:r.replace(/\$(\d)/g,(function(t,n){return e[n]}))),l()};l()}}))}))}e.commands.find=function(e){d(e),u(e)},e.commands.findPersistent=function(e){d(e),u(e,!1,!0)},e.commands.findPersistentNext=function(e){u(e,!1,!0,!0)},e.commands.findPersistentPrev=function(e){u(e,!0,!0,!0)},e.commands.findNext=u,e.commands.findPrev=function(e){u(e,!0)},e.commands.clearSearch=d,e.commands.replace=p,e.commands.replaceAll=function(e){p(e,!0)}}(n(0),n(1),n(4))},function(e,t,n){!function(e){"use strict";var t={style:"matchhighlight",minChars:2,delay:100,wordsOnly:!1,annotateScrollbar:!1,showToken:!1,trim:!0};function n(e){for(var n in this.options={},t)this.options[n]=(e&&e.hasOwnProperty(n)?e:t)[n];this.overlay=this.timeout=null,this.matchesonscroll=null,this.active=!1}function r(e){var t=e.state.matchHighlighter;(t.active||e.hasFocus())&&o(e,t)}function i(e){var t=e.state.matchHighlighter;t.active||(t.active=!0,o(e,t))}function o(e,t){clearTimeout(t.timeout),t.timeout=setTimeout((function(){s(e)}),t.options.delay)}function a(e,t,n,r){var i=e.state.matchHighlighter;if(e.addOverlay(i.overlay=function(e,t,n){return{token:function(r){if(r.match(e)&&(!t||function(e,t){return!(e.start&&t.test(e.string.charAt(e.start-1))||e.pos!=e.string.length&&t.test(e.string.charAt(e.pos)))}(r,t)))return n;r.next(),r.skipTo(e.charAt(0))||r.skipToEnd()}}}(t,n,r)),i.options.annotateScrollbar&&e.showMatchesOnScrollbar){var o=n?new RegExp("\\b"+t.replace(/[\\\[.+*?(){|^$]/g,"\\$&")+"\\b"):t;i.matchesonscroll=e.showMatchesOnScrollbar(o,!1,{className:"CodeMirror-selection-highlight-scrollbar"})}}function l(e){var t=e.state.matchHighlighter;t.overlay&&(e.removeOverlay(t.overlay),t.overlay=null,t.matchesonscroll&&(t.matchesonscroll.clear(),t.matchesonscroll=null))}function s(e){e.operation((function(){var t=e.state.matchHighlighter;if(l(e),e.somethingSelected()||!t.options.showToken){var n=e.getCursor("from"),r=e.getCursor("to");if(n.line==r.line&&(!t.options.wordsOnly||function(e,t,n){if(null!==e.getRange(t,n).match(/^\w+$/)){if(t.ch>0){var r={line:t.line,ch:t.ch-1};if(null===e.getRange(r,t).match(/\W/))return!1}return!(n.ch<e.getLine(t.line).length&&(r={line:n.line,ch:n.ch+1},null===e.getRange(n,r).match(/\W/)))}return!1}(e,n,r))){var i=e.getRange(n,r);t.options.trim&&(i=i.replace(/^\s+|\s+$/g,"")),i.length>=t.options.minChars&&a(e,i,!1,t.options.style)}}else{for(var o=!0===t.options.showToken?/[\w$]/:t.options.showToken,s=e.getCursor(),c=e.getLine(s.line),u=s.ch,f=u;u&&o.test(c.charAt(u-1));)--u;for(;f<c.length&&o.test(c.charAt(f));)++f;u<f&&a(e,c.slice(u,f),o,t.options.style)}}))}e.defineOption("highlightSelectionMatches",!1,(function(t,o,a){if(a&&a!=e.Init&&(l(t),clearTimeout(t.state.matchHighlighter.timeout),t.state.matchHighlighter=null,t.off("cursorActivity",r),t.off("focus",i)),o){var c=t.state.matchHighlighter=new n(o);t.hasFocus()?(c.active=!0,s(t)):t.on("focus",i),t.on("cursorActivity",r)}}))}(n(0),n(10))},function(e,t,n){!function(e){"use strict";function t(e,t,n,r){this.cm=e,this.options=r;var i={listenForChanges:!1};for(var o in r)i[o]=r[o];i.className||(i.className="CodeMirror-search-match"),this.annotation=e.annotateScrollbar(i),this.query=t,this.caseFold=n,this.gap={from:e.firstLine(),to:e.lastLine()+1},this.matches=[],this.update=null,this.findMatches(),this.annotation.update(this.matches);var a=this;e.on("change",this.changeHandler=function(e,t){a.onChange(t)})}function n(e,t,n){return e<=t?e:Math.max(t,e+n)}e.defineExtension("showMatchesOnScrollbar",(function(e,n,r){return"string"==typeof r&&(r={className:r}),r||(r={}),new t(this,e,n,r)})),t.prototype.findMatches=function(){if(this.gap){for(var t=0;t<this.matches.length&&!((i=this.matches[t]).from.line>=this.gap.to);t++)i.to.line>=this.gap.from&&this.matches.splice(t--,1);for(var n=this.cm.getSearchCursor(this.query,e.Pos(this.gap.from,0),{caseFold:this.caseFold,multiline:this.options.multiline}),r=this.options&&this.options.maxMatches||1e3;n.findNext();){var i;if((i={from:n.from(),to:n.to()}).from.line>=this.gap.to)break;if(this.matches.splice(t++,0,i),this.matches.length>r)break}this.gap=null}},t.prototype.onChange=function(t){var r=t.from.line,i=e.changeEnd(t).line,o=i-t.to.line;if(this.gap?(this.gap.from=Math.min(n(this.gap.from,r,o),t.from.line),this.gap.to=Math.max(n(this.gap.to,r,o),t.from.line)):this.gap={from:t.from.line,to:i+1},o)for(var a=0;a<this.matches.length;a++){var l=this.matches[a],s=n(l.from.line,r,o);s!=l.from.line&&(l.from=e.Pos(s,l.from.ch));var c=n(l.to.line,r,o);c!=l.to.line&&(l.to=e.Pos(c,l.to.ch))}clearTimeout(this.update);var u=this;this.update=setTimeout((function(){u.updateAfterChange()}),250)},t.prototype.updateAfterChange=function(){this.findMatches(),this.annotation.update(this.matches)},t.prototype.clear=function(){this.cm.off("change",this.changeHandler),this.annotation.clear()}}(n(0),n(1),n(11))},function(e,t,n){!function(e){"use strict";function t(e,t){function n(e){clearTimeout(r.doRedraw),r.doRedraw=setTimeout((function(){r.redraw()}),e)}this.cm=e,this.options=t,this.buttonHeight=t.scrollButtonHeight||e.getOption("scrollButtonHeight"),this.annotations=[],this.doRedraw=this.doUpdate=null,this.div=e.getWrapperElement().appendChild(document.createElement("div")),this.div.style.cssText="position: absolute; right: 0; top: 0; z-index: 7; pointer-events: none",this.computeScale();var r=this;e.on("refresh",this.resizeHandler=function(){clearTimeout(r.doUpdate),r.doUpdate=setTimeout((function(){r.computeScale()&&n(20)}),100)}),e.on("markerAdded",this.resizeHandler),e.on("markerCleared",this.resizeHandler),!1!==t.listenForChanges&&e.on("changes",this.changeHandler=function(){n(250)})}e.defineExtension("annotateScrollbar",(function(e){return"string"==typeof e&&(e={className:e}),new t(this,e)})),e.defineOption("scrollButtonHeight",0),t.prototype.computeScale=function(){var e=this.cm,t=(e.getWrapperElement().clientHeight-e.display.barHeight-2*this.buttonHeight)/e.getScrollerElement().scrollHeight;if(t!=this.hScale)return this.hScale=t,!0},t.prototype.update=function(e){this.annotations=e,this.redraw()},t.prototype.redraw=function(e){!1!==e&&this.computeScale();var t=this.cm,n=this.hScale,r=document.createDocumentFragment(),i=this.annotations,o=t.getOption("lineWrapping"),a=o&&1.5*t.defaultTextHeight(),l=null,s=null;function c(e,n){if(l!=e.line){l=e.line,s=t.getLineHandle(e.line);var r=t.getLineHandleVisualStart(s);r!=s&&(l=t.getLineNumber(r),s=r)}return s.widgets&&s.widgets.length||o&&s.height>a?t.charCoords(e,"local")[n?"top":"bottom"]:t.heightAtLine(s,"local")+(n?0:s.height)}var u=t.lastLine();if(t.display.barWidth)for(var f,d=0;d<i.length;d++){var h=i[d];if(!(h.to.line>u)){for(var p=f||c(h.from,!0)*n,m=c(h.to,!1)*n;d<i.length-1&&!(i[d+1].to.line>u)&&!((f=c(i[d+1].from,!0)*n)>m+.9);)m=c((h=i[++d]).to,!1)*n;if(m!=p){var g=Math.max(m-p,3),v=r.appendChild(document.createElement("div"));v.style.cssText="position: absolute; right: 0px; width: "+Math.max(t.display.barWidth-1,2)+"px; top: "+(p+this.buttonHeight)+"px; height: "+g+"px",v.className=this.options.className,h.id&&v.setAttribute("annotation-id",h.id)}}}this.div.textContent="",this.div.appendChild(r)},t.prototype.clear=function(){this.cm.off("refresh",this.resizeHandler),this.cm.off("markerAdded",this.resizeHandler),this.cm.off("markerCleared",this.resizeHandler),this.changeHandler&&this.cm.off("changes",this.changeHandler),this.div.parentNode.removeChild(this.div)}}(n(0))},function(e,t,n){!function(e){var t=/MSIE \d/.test(navigator.userAgent)&&(null==document.documentMode||document.documentMode<8),n=e.Pos,r={"(":")>",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<","<":">>",">":"<<"};function i(e){return e&&e.bracketRegex||/[(){}[\]]/}function o(e,t,o){var l=e.getLineHandle(t.line),s=t.ch-1,c=o&&o.afterCursor;null==c&&(c=/(^| )cm-fat-cursor($| )/.test(e.getWrapperElement().className));var u=i(o),f=!c&&s>=0&&u.test(l.text.charAt(s))&&r[l.text.charAt(s)]||u.test(l.text.charAt(s+1))&&r[l.text.charAt(++s)];if(!f)return null;var d=">"==f.charAt(1)?1:-1;if(o&&o.strict&&d>0!=(s==t.ch))return null;var h=e.getTokenTypeAt(n(t.line,s+1)),p=a(e,n(t.line,s+(d>0?1:0)),d,h||null,o);return null==p?null:{from:n(t.line,s),to:p&&p.pos,match:p&&p.ch==f.charAt(0),forward:d>0}}function a(e,t,o,a,l){for(var s=l&&l.maxScanLineLength||1e4,c=l&&l.maxScanLines||1e3,u=[],f=i(l),d=o>0?Math.min(t.line+c,e.lastLine()+1):Math.max(e.firstLine()-1,t.line-c),h=t.line;h!=d;h+=o){var p=e.getLine(h);if(p){var m=o>0?0:p.length-1,g=o>0?p.length:-1;if(!(p.length>s))for(h==t.line&&(m=t.ch-(o<0?1:0));m!=g;m+=o){var v=p.charAt(m);if(f.test(v)&&(void 0===a||e.getTokenTypeAt(n(h,m+1))==a)){var y=r[v];if(y&&">"==y.charAt(1)==o>0)u.push(v);else{if(!u.length)return{pos:n(h,m),ch:v};u.pop()}}}}}return h-o!=(o>0?e.lastLine():e.firstLine())&&null}function l(e,r,i){for(var a=e.state.matchBrackets.maxHighlightLineLength||1e3,l=[],s=e.listSelections(),c=0;c<s.length;c++){var u=s[c].empty()&&o(e,s[c].head,i);if(u&&e.getLine(u.from.line).length<=a){var f=u.match?"CodeMirror-matchingbracket":"CodeMirror-nonmatchingbracket";l.push(e.markText(u.from,n(u.from.line,u.from.ch+1),{className:f})),u.to&&e.getLine(u.to.line).length<=a&&l.push(e.markText(u.to,n(u.to.line,u.to.ch+1),{className:f}))}}if(l.length){t&&e.state.focused&&e.focus();var d=function(){e.operation((function(){for(var e=0;e<l.length;e++)l[e].clear()}))};if(!r)return d;setTimeout(d,800)}}function s(e){e.operation((function(){e.state.matchBrackets.currentlyHighlighted&&(e.state.matchBrackets.currentlyHighlighted(),e.state.matchBrackets.currentlyHighlighted=null),e.state.matchBrackets.currentlyHighlighted=l(e,!1,e.state.matchBrackets)}))}e.defineOption("matchBrackets",!1,(function(t,n,r){r&&r!=e.Init&&(t.off("cursorActivity",s),t.state.matchBrackets&&t.state.matchBrackets.currentlyHighlighted&&(t.state.matchBrackets.currentlyHighlighted(),t.state.matchBrackets.currentlyHighlighted=null)),n&&(t.state.matchBrackets="object"==typeof n?n:{},t.on("cursorActivity",s))})),e.defineExtension("matchBrackets",(function(){l(this,!0)})),e.defineExtension("findMatchingBracket",(function(e,t,n){return(n||"boolean"==typeof t)&&(n?(n.strict=t,t=n):t=t?{strict:!0}:null),o(this,e,t)})),e.defineExtension("scanForBracket",(function(e,t,n,r){return a(this,e,t,n,r)}))}(n(0))},function(e,t,n){!function(e){var t={pairs:"()[]{}''\"\"",closeBefore:")]}'\":;>",triples:"",explode:"[]{}"},n=e.Pos;function r(e,n){return"pairs"==n&&"string"==typeof e?e:"object"==typeof e&&null!=e[n]?e[n]:t[n]}e.defineOption("autoCloseBrackets",!1,(function(t,n,a){a&&a!=e.Init&&(t.removeKeyMap(i),t.state.closeBrackets=null),n&&(o(r(n,"pairs")),t.state.closeBrackets=n,t.addKeyMap(i))}));var i={Backspace:function(t){var i=l(t);if(!i||t.getOption("disableInput"))return e.Pass;for(var o=r(i,"pairs"),a=t.listSelections(),c=0;c<a.length;c++){if(!a[c].empty())return e.Pass;var u=s(t,a[c].head);if(!u||o.indexOf(u)%2!=0)return e.Pass}for(c=a.length-1;c>=0;c--){var f=a[c].head;t.replaceRange("",n(f.line,f.ch-1),n(f.line,f.ch+1),"+delete")}},Enter:function(t){var n=l(t),i=n&&r(n,"explode");if(!i||t.getOption("disableInput"))return e.Pass;for(var o=t.listSelections(),a=0;a<o.length;a++){if(!o[a].empty())return e.Pass;var c=s(t,o[a].head);if(!c||i.indexOf(c)%2!=0)return e.Pass}t.operation((function(){var e=t.lineSeparator()||"\n";t.replaceSelection(e+e,null),t.execCommand("goCharLeft"),o=t.listSelections();for(var n=0;n<o.length;n++){var r=o[n].head.line;t.indentLine(r,null,!0),t.indentLine(r+1,null,!0)}}))}};function o(e){for(var t=0;t<e.length;t++){var n=e.charAt(t),r="'"+n+"'";i[r]||(i[r]=a(n))}}function a(t){return function(i){return function(t,i){var o=l(t);if(!o||t.getOption("disableInput"))return e.Pass;var a=r(o,"pairs"),s=a.indexOf(i);if(-1==s)return e.Pass;for(var u,f=r(o,"closeBefore"),d=r(o,"triples"),h=a.charAt(s+1)==i,p=t.listSelections(),m=s%2==0,g=0;g<p.length;g++){var v,y=p[g],b=y.head,x=t.getRange(b,n(b.line,b.ch+1));if(m&&!y.empty())v="surround";else if(!h&&m||x!=i)if(h&&b.ch>1&&d.indexOf(i)>=0&&t.getRange(n(b.line,b.ch-2),b)==i+i){if(b.ch>2&&/\bstring/.test(t.getTokenTypeAt(n(b.line,b.ch-2))))return e.Pass;v="addFour"}else if(h){var w=0==b.ch?" ":t.getRange(n(b.line,b.ch-1),b);if(e.isWordChar(x)||w==i||e.isWordChar(w))return e.Pass;v="both"}else{if(!m||!(0===x.length||/\s/.test(x)||f.indexOf(x)>-1))return e.Pass;v="both"}else v=h&&c(t,b)?"both":d.indexOf(i)>=0&&t.getRange(b,n(b.line,b.ch+3))==i+i+i?"skipThree":"skip";if(u){if(u!=v)return e.Pass}else u=v}var k=s%2?a.charAt(s-1):i,C=s%2?i:a.charAt(s+1);t.operation((function(){if("skip"==u)t.execCommand("goCharRight");else if("skipThree"==u)for(var r=0;r<3;r++)t.execCommand("goCharRight");else if("surround"==u){var i=t.getSelections();for(r=0;r<i.length;r++)i[r]=k+i[r]+C;for(t.replaceSelections(i,"around"),i=t.listSelections().slice(),r=0;r<i.length;r++)i[r]=(o=i[r],a=void 0,a=e.cmpPos(o.anchor,o.head)>0,{anchor:new n(o.anchor.line,o.anchor.ch+(a?-1:1)),head:new n(o.head.line,o.head.ch+(a?1:-1))});t.setSelections(i)}else"both"==u?(t.replaceSelection(k+C,null),t.triggerElectric(k+C),t.execCommand("goCharLeft")):"addFour"==u&&(t.replaceSelection(k+k+k+k,"before"),t.execCommand("goCharRight"));var o,a}))}(i,t)}}function l(e){var t=e.state.closeBrackets;return!t||t.override?t:e.getModeAt(e.getCursor()).closeBrackets||t}function s(e,t){var r=e.getRange(n(t.line,t.ch-1),n(t.line,t.ch+1));return 2==r.length?r:null}function c(e,t){var r=e.getTokenAt(n(t.line,t.ch+1));return/\bstring/.test(r.type)&&r.start==t.ch&&(0==t.ch||!/\bstring/.test(e.getTokenTypeAt(t)))}o(t.pairs+"`")}(n(0))},function(e,t,n){!function(e){"use strict";var t={},n=/[^\s\u00a0]/,r=e.Pos;function i(e){var t=e.search(n);return-1==t?0:t}function o(e,t){var n=e.getMode();return!1!==n.useInnerComments&&n.innerMode?e.getModeAt(t):n}e.commands.toggleComment=function(e){e.toggleComment()},e.defineExtension("toggleComment",(function(e){e||(e=t);for(var n=1/0,i=this.listSelections(),o=null,a=i.length-1;a>=0;a--){var l=i[a].from(),s=i[a].to();l.line>=n||(s.line>=n&&(s=r(n,0)),n=l.line,null==o?this.uncomment(l,s,e)?o="un":(this.lineComment(l,s,e),o="line"):"un"==o?this.uncomment(l,s,e):this.lineComment(l,s,e))}})),e.defineExtension("lineComment",(function(e,a,l){l||(l=t);var s=this,c=o(s,e),u=s.getLine(e.line);if(null!=u&&(f=e,d=u,!/\bstring\b/.test(s.getTokenTypeAt(r(f.line,0)))||/^[\'\"\`]/.test(d))){var f,d,h=l.lineComment||c.lineComment;if(h){var p=Math.min(0!=a.ch||a.line==e.line?a.line+1:a.line,s.lastLine()+1),m=null==l.padding?" ":l.padding,g=l.commentBlankLines||e.line==a.line;s.operation((function(){if(l.indent){for(var t=null,o=e.line;o<p;++o){var a=(c=s.getLine(o)).slice(0,i(c));(null==t||t.length>a.length)&&(t=a)}for(o=e.line;o<p;++o){var c=s.getLine(o),u=t.length;(g||n.test(c))&&(c.slice(0,u)!=t&&(u=i(c)),s.replaceRange(t+h+m,r(o,0),r(o,u)))}}else for(o=e.line;o<p;++o)(g||n.test(s.getLine(o)))&&s.replaceRange(h+m,r(o,0))}))}else(l.blockCommentStart||c.blockCommentStart)&&(l.fullLines=!0,s.blockComment(e,a,l))}})),e.defineExtension("blockComment",(function(e,i,a){a||(a=t);var l=this,s=o(l,e),c=a.blockCommentStart||s.blockCommentStart,u=a.blockCommentEnd||s.blockCommentEnd;if(c&&u){if(!/\bcomment\b/.test(l.getTokenTypeAt(r(e.line,0)))){var f=Math.min(i.line,l.lastLine());f!=e.line&&0==i.ch&&n.test(l.getLine(f))&&--f;var d=null==a.padding?" ":a.padding;e.line>f||l.operation((function(){if(0!=a.fullLines){var t=n.test(l.getLine(f));l.replaceRange(d+u,r(f)),l.replaceRange(c+d,r(e.line,0));var o=a.blockCommentLead||s.blockCommentLead;if(null!=o)for(var h=e.line+1;h<=f;++h)(h!=f||t)&&l.replaceRange(o+d,r(h,0))}else l.replaceRange(u,i),l.replaceRange(c,e)}))}}else(a.lineComment||s.lineComment)&&0!=a.fullLines&&l.lineComment(e,i,a)})),e.defineExtension("uncomment",(function(e,i,a){a||(a=t);var l,s=this,c=o(s,e),u=Math.min(0!=i.ch||i.line==e.line?i.line:i.line-1,s.lastLine()),f=Math.min(e.line,u),d=a.lineComment||c.lineComment,h=[],p=null==a.padding?" ":a.padding;e:if(d){for(var m=f;m<=u;++m){var g=s.getLine(m),v=g.indexOf(d);if(v>-1&&!/comment/.test(s.getTokenTypeAt(r(m,v+1)))&&(v=-1),-1==v&&n.test(g))break e;if(v>-1&&n.test(g.slice(0,v)))break e;h.push(g)}if(s.operation((function(){for(var e=f;e<=u;++e){var t=h[e-f],n=t.indexOf(d),i=n+d.length;n<0||(t.slice(i,i+p.length)==p&&(i+=p.length),l=!0,s.replaceRange("",r(e,n),r(e,i)))}})),l)return!0}var y=a.blockCommentStart||c.blockCommentStart,b=a.blockCommentEnd||c.blockCommentEnd;if(!y||!b)return!1;var x=a.blockCommentLead||c.blockCommentLead,w=s.getLine(f),k=w.indexOf(y);if(-1==k)return!1;var C=u==f?w:s.getLine(u),S=C.indexOf(b,u==f?k+y.length:0),T=r(f,k+1),L=r(u,S+1);if(-1==S||!/comment/.test(s.getTokenTypeAt(T))||!/comment/.test(s.getTokenTypeAt(L))||s.getRange(T,L,"\n").indexOf(b)>-1)return!1;var M=w.lastIndexOf(y,e.ch),O=-1==M?-1:w.slice(0,e.ch).indexOf(b,M+y.length);if(-1!=M&&-1!=O&&O+b.length!=e.ch)return!1;O=C.indexOf(b,i.ch);var N=C.slice(i.ch).lastIndexOf(y,O-i.ch);return M=-1==O||-1==N?-1:i.ch+N,(-1==O||-1==M||M==i.ch)&&(s.operation((function(){s.replaceRange("",r(u,S-(p&&C.slice(S-p.length,S)==p?p.length:0)),r(u,S+b.length));var e=k+y.length;if(p&&w.slice(e,e+p.length)==p&&(e+=p.length),s.replaceRange("",r(f,k),r(f,e)),x)for(var t=f+1;t<=u;++t){var i=s.getLine(t),o=i.indexOf(x);if(-1!=o&&!n.test(i.slice(0,o))){var a=o+x.length;p&&i.slice(a,a+p.length)==p&&(a+=p.length),s.replaceRange("",r(t,o),r(t,a))}}})),!0)}))}(n(0))},function(e,t,n){!function(e){e.inputStyles.accessibleTextArea=class extends e.inputStyles.textarea{init(e){super.init(e),this.textarea.addEventListener("compositionstart",this._onCompositionStart.bind(this))}_onCompositionStart(){if(this.textarea.selectionEnd===this.textarea.value.length)return;this.textarea.value=this.textarea.value.substring(0,this.textarea.selectionEnd);const e=this.textarea.value.length;this.textarea.setSelectionRange(e,e),this.prevInput=this.textarea.value}reset(e){if(e||this.contextMenuPending||this.composing||this.cm.somethingSelected())return void super.reset(e);const t=this.cm.getCursor();let n,r;if(this.cm.options.lineWrapping){const e=this.cm.charCoords(t,"page").top;n=this.cm.coordsChar({left:-1/0,top:e}),r=this.cm.coordsChar({left:1/0,top:e})}else{const e=1e3*Math.floor(t.ch/1e3);n={ch:e,line:t.line},r={ch:e+1e3,line:t.line}}this.textarea.value=this.cm.getRange(n,r);const i=t.ch-n.ch;this.textarea.setSelectionRange(i,i),this.prevInput=this.textarea.value}poll(){if(this.contextMenuPending||this.composing)return super.poll();const e=this.textarea.value;let t=0;const n=Math.min(this.prevInput.length,e.length);for(;t<n&&this.prevInput[t]===e[t];)++t;let r=0;for(;r<n-t&&this.prevInput[this.prevInput.length-r-1]===e[e.length-r-1];)++r;const i=this.textarea;this.textarea=document.createElement("textarea"),this.textarea.value=e.substring(t,e.length-r),this.textarea.setSelectionRange(i.selectionStart-t,i.selectionEnd-t),this.prevInput="";const o=super.poll();return this.prevInput=e,this.textarea=i,o}}}(n(0))},function(e,t,n){!function(e){"use strict";e.defineMode("clojure",(function(t){var n=["false","nil","true"],r=[".","catch","def","do","if","monitor-enter","monitor-exit","new","quote","recur","set!","throw","try","var"],i=["*","*'","*1","*2","*3","*agent*","*allow-unresolved-vars*","*assert*","*clojure-version*","*command-line-args*","*compile-files*","*compile-path*","*compiler-options*","*data-readers*","*default-data-reader-fn*","*e","*err*","*file*","*flush-on-newline*","*fn-loader*","*in*","*math-context*","*ns*","*out*","*print-dup*","*print-length*","*print-level*","*print-meta*","*print-namespace-maps*","*print-readably*","*read-eval*","*reader-resolver*","*source-path*","*suppress-read*","*unchecked-math*","*use-context-classloader*","*verbose-defrecords*","*warn-on-reflection*","+","+'","-","-'","->","->>","->ArrayChunk","->Eduction","->Vec","->VecNode","->VecSeq","-cache-protocol-fn","-reset-methods","..","/","<","<=","=","==",">",">=","EMPTY-NODE","Inst","StackTraceElement->vec","Throwable->map","accessor","aclone","add-classpath","add-watch","agent","agent-error","agent-errors","aget","alength","alias","all-ns","alter","alter-meta!","alter-var-root","amap","ancestors","and","any?","apply","areduce","array-map","as->","aset","aset-boolean","aset-byte","aset-char","aset-double","aset-float","aset-int","aset-long","aset-short","assert","assoc","assoc!","assoc-in","associative?","atom","await","await-for","await1","bases","bean","bigdec","bigint","biginteger","binding","bit-and","bit-and-not","bit-clear","bit-flip","bit-not","bit-or","bit-set","bit-shift-left","bit-shift-right","bit-test","bit-xor","boolean","boolean-array","boolean?","booleans","bound-fn","bound-fn*","bound?","bounded-count","butlast","byte","byte-array","bytes","bytes?","case","cast","cat","char","char-array","char-escape-string","char-name-string","char?","chars","chunk","chunk-append","chunk-buffer","chunk-cons","chunk-first","chunk-next","chunk-rest","chunked-seq?","class","class?","clear-agent-errors","clojure-version","coll?","comment","commute","comp","comparator","compare","compare-and-set!","compile","complement","completing","concat","cond","cond->","cond->>","condp","conj","conj!","cons","constantly","construct-proxy","contains?","count","counted?","create-ns","create-struct","cycle","dec","dec'","decimal?","declare","dedupe","default-data-readers","definline","definterface","defmacro","defmethod","defmulti","defn","defn-","defonce","defprotocol","defrecord","defstruct","deftype","delay","delay?","deliver","denominator","deref","derive","descendants","destructure","disj","disj!","dissoc","dissoc!","distinct","distinct?","doall","dorun","doseq","dosync","dotimes","doto","double","double-array","double?","doubles","drop","drop-last","drop-while","eduction","empty","empty?","ensure","ensure-reduced","enumeration-seq","error-handler","error-mode","eval","even?","every-pred","every?","ex-data","ex-info","extend","extend-protocol","extend-type","extenders","extends?","false?","ffirst","file-seq","filter","filterv","find","find-keyword","find-ns","find-protocol-impl","find-protocol-method","find-var","first","flatten","float","float-array","float?","floats","flush","fn","fn?","fnext","fnil","for","force","format","frequencies","future","future-call","future-cancel","future-cancelled?","future-done?","future?","gen-class","gen-interface","gensym","get","get-in","get-method","get-proxy-class","get-thread-bindings","get-validator","group-by","halt-when","hash","hash-combine","hash-map","hash-ordered-coll","hash-set","hash-unordered-coll","ident?","identical?","identity","if-let","if-not","if-some","ifn?","import","in-ns","inc","inc'","indexed?","init-proxy","inst-ms","inst-ms*","inst?","instance?","int","int-array","int?","integer?","interleave","intern","interpose","into","into-array","ints","io!","isa?","iterate","iterator-seq","juxt","keep","keep-indexed","key","keys","keyword","keyword?","last","lazy-cat","lazy-seq","let","letfn","line-seq","list","list*","list?","load","load-file","load-reader","load-string","loaded-libs","locking","long","long-array","longs","loop","macroexpand","macroexpand-1","make-array","make-hierarchy","map","map-entry?","map-indexed","map?","mapcat","mapv","max","max-key","memfn","memoize","merge","merge-with","meta","method-sig","methods","min","min-key","mix-collection-hash","mod","munge","name","namespace","namespace-munge","nat-int?","neg-int?","neg?","newline","next","nfirst","nil?","nnext","not","not-any?","not-empty","not-every?","not=","ns","ns-aliases","ns-imports","ns-interns","ns-map","ns-name","ns-publics","ns-refers","ns-resolve","ns-unalias","ns-unmap","nth","nthnext","nthrest","num","number?","numerator","object-array","odd?","or","parents","partial","partition","partition-all","partition-by","pcalls","peek","persistent!","pmap","pop","pop!","pop-thread-bindings","pos-int?","pos?","pr","pr-str","prefer-method","prefers","primitives-classnames","print","print-ctor","print-dup","print-method","print-simple","print-str","printf","println","println-str","prn","prn-str","promise","proxy","proxy-call-with-super","proxy-mappings","proxy-name","proxy-super","push-thread-bindings","pvalues","qualified-ident?","qualified-keyword?","qualified-symbol?","quot","rand","rand-int","rand-nth","random-sample","range","ratio?","rational?","rationalize","re-find","re-groups","re-matcher","re-matches","re-pattern","re-seq","read","read-line","read-string","reader-conditional","reader-conditional?","realized?","record?","reduce","reduce-kv","reduced","reduced?","reductions","ref","ref-history-count","ref-max-history","ref-min-history","ref-set","refer","refer-clojure","reify","release-pending-sends","rem","remove","remove-all-methods","remove-method","remove-ns","remove-watch","repeat","repeatedly","replace","replicate","require","reset!","reset-meta!","reset-vals!","resolve","rest","restart-agent","resultset-seq","reverse","reversible?","rseq","rsubseq","run!","satisfies?","second","select-keys","send","send-off","send-via","seq","seq?","seqable?","seque","sequence","sequential?","set","set-agent-send-executor!","set-agent-send-off-executor!","set-error-handler!","set-error-mode!","set-validator!","set?","short","short-array","shorts","shuffle","shutdown-agents","simple-ident?","simple-keyword?","simple-symbol?","slurp","some","some->","some->>","some-fn","some?","sort","sort-by","sorted-map","sorted-map-by","sorted-set","sorted-set-by","sorted?","special-symbol?","spit","split-at","split-with","str","string?","struct","struct-map","subs","subseq","subvec","supers","swap!","swap-vals!","symbol","symbol?","sync","tagged-literal","tagged-literal?","take","take-last","take-nth","take-while","test","the-ns","thread-bound?","time","to-array","to-array-2d","trampoline","transduce","transient","tree-seq","true?","type","unchecked-add","unchecked-add-int","unchecked-byte","unchecked-char","unchecked-dec","unchecked-dec-int","unchecked-divide-int","unchecked-double","unchecked-float","unchecked-inc","unchecked-inc-int","unchecked-int","unchecked-long","unchecked-multiply","unchecked-multiply-int","unchecked-negate","unchecked-negate-int","unchecked-remainder-int","unchecked-short","unchecked-subtract","unchecked-subtract-int","underive","unquote","unquote-splicing","unreduced","unsigned-bit-shift-right","update","update-in","update-proxy","uri?","use","uuid?","val","vals","var-get","var-set","var?","vary-meta","vec","vector","vector-of","vector?","volatile!","volatile?","vreset!","vswap!","when","when-first","when-let","when-not","when-some","while","with-bindings","with-bindings*","with-in-str","with-loading-context","with-local-vars","with-meta","with-open","with-out-str","with-precision","with-redefs","with-redefs-fn","xml-seq","zero?","zipmap"];e.registerHelper("hintWords","clojure",[].concat(n,r,i));var o=g(n),a=g(r),l=g(i),s=g(["->","->>","as->","binding","bound-fn","case","catch","comment","cond","cond->","cond->>","condp","def","definterface","defmethod","defn","defmacro","defprotocol","defrecord","defstruct","deftype","do","doseq","dotimes","doto","extend","extend-protocol","extend-type","fn","for","future","if","if-let","if-not","if-some","let","letfn","locking","loop","ns","proxy","reify","struct-map","some->","some->>","try","when","when-first","when-let","when-not","when-some","while","with-bindings","with-bindings*","with-in-str","with-loading-context","with-local-vars","with-meta","with-open","with-out-str","with-precision","with-redefs","with-redefs-fn"]),c=/^(?:[\\\[\]\s"(),;@^`{}~]|$)/,u=/^(?:[+\-]?\d+(?:(?:N|(?:[eE][+\-]?\d+))|(?:\.?\d*(?:M|(?:[eE][+\-]?\d+))?)|\/\d+|[xX][0-9a-fA-F]+|r[0-9a-zA-Z]+)?(?=[\\\[\]\s"#'(),;@^`{}~]|$))/,f=/^(?:\\(?:backspace|formfeed|newline|return|space|tab|o[0-7]{3}|u[0-9A-Fa-f]{4}|x[0-9A-Fa-f]{4}|.)?(?=[\\\[\]\s"(),;@^`{}~]|$))/,d=/^(?:(?:[^\\\/\[\]\d\s"#'(),;@^`{}~][^\\\[\]\s"(),;@^`{}~]*(?:\.[^\\\/\[\]\d\s"#'(),;@^`{}~][^\\\[\]\s"(),;@^`{}~]*)*\/)?(?:\/|[^\\\/\[\]\d\s"#'(),;@^`{}~][^\\\[\]\s"(),;@^`{}~]*)*(?=[\\\[\]\s"(),;@^`{}~]|$))/;function h(e,t){if(e.eatSpace()||e.eat(","))return["space",null];if(e.match(u))return[null,"number"];if(e.match(f))return[null,"string-2"];if(e.eat(/^"/))return(t.tokenize=p)(e,t);if(e.eat(/^[(\[{]/))return["open","bracket"];if(e.eat(/^[)\]}]/))return["close","bracket"];if(e.eat(/^;/))return e.skipToEnd(),["space","comment"];if(e.eat(/^[#'@^`~]/))return[null,"meta"];var n=e.match(d),r=n&&n[0];return r?"comment"===r&&"("===t.lastToken?(t.tokenize=m)(e,t):v(r,o)||":"===r.charAt(0)?["symbol","atom"]:v(r,a)||v(r,l)?["symbol","keyword"]:"("===t.lastToken?["symbol","builtin"]:["symbol","variable"]:(e.next(),e.eatWhile((function(e){return!v(e,c)})),[null,"error"])}function p(e,t){for(var n,r=!1;n=e.next();){if('"'===n&&!r){t.tokenize=h;break}r=!r&&"\\"===n}return[null,"string"]}function m(e,t){for(var n,r=1;n=e.next();)if(")"===n&&r--,"("===n&&r++,0===r){e.backUp(1),t.tokenize=h;break}return["space","comment"]}function g(e){for(var t={},n=0;n<e.length;++n)t[e[n]]=!0;return t}function v(e,t){return t instanceof RegExp?t.test(e):t instanceof Object?t.propertyIsEnumerable(e):void 0}return{startState:function(){return{ctx:{prev:null,start:0,indentTo:0},lastToken:null,tokenize:h}},token:function(e,n){e.sol()&&"number"!=typeof n.ctx.indentTo&&(n.ctx.indentTo=n.ctx.start+1);var r=n.tokenize(e,n),i=r[0],o=r[1],a=e.current();return"space"!==i&&("("===n.lastToken&&null===n.ctx.indentTo?"symbol"===i&&v(a,s)?n.ctx.indentTo=n.ctx.start+t.indentUnit:n.ctx.indentTo="next":"next"===n.ctx.indentTo&&(n.ctx.indentTo=e.column()),n.lastToken=a),"open"===i?n.ctx={prev:n.ctx,start:e.column(),indentTo:null}:"close"===i&&(n.ctx=n.ctx.prev||n.ctx),o},indent:function(e){var t=e.ctx.indentTo;return"number"==typeof t?t:e.ctx.start+1},closeBrackets:{pairs:'()[]{}""'},lineComment:";;"}})),e.defineMIME("text/x-clojure","clojure"),e.defineMIME("text/x-clojurescript","clojure"),e.defineMIME("application/edn","clojure")}(n(0))},function(e,t,n){!function(e){"use strict";e.defineMode("haxe",(function(e,t){var n=e.indentUnit;function r(e){return{type:e,style:"keyword"}}var i,o=r("keyword a"),a=r("keyword b"),l=r("keyword c"),s=r("operator"),c={type:"atom",style:"atom"},u={type:"attribute",style:"attribute"},f=r("typedef"),d={if:o,while:o,else:a,do:a,try:a,return:l,break:l,continue:l,new:l,throw:l,var:r("var"),inline:u,static:u,using:r("import"),public:u,private:u,cast:r("cast"),import:r("import"),macro:r("macro"),function:r("function"),catch:r("catch"),untyped:r("untyped"),callback:r("cb"),for:r("for"),switch:r("switch"),case:r("case"),default:r("default"),in:s,never:r("property_access"),trace:r("trace"),class:f,abstract:f,enum:f,interface:f,typedef:f,extends:f,implements:f,dynamic:f,true:c,false:c,null:c},h=/[+\-*&%=<>!?|]/;function p(e,t,n){return t.tokenize=n,n(e,t)}function m(e,t){for(var n,r=!1;null!=(n=e.next());){if(n==t&&!r)return!0;r=!r&&"\\"==n}}function g(e,t,n){return f=e,i=n,t}function v(e,t){var n=e.next();if('"'==n||"'"==n)return p(e,t,(r=n,function(e,t){return m(e,r)&&(t.tokenize=v),g("string","string")}));if(/[\[\]{}\(\),;\:\.]/.test(n))return g(n);if("0"==n&&e.eat(/x/i))return e.eatWhile(/[\da-f]/i),g("number","number");if(/\d/.test(n)||"-"==n&&e.eat(/\d/))return e.match(/^\d*(?:\.\d*(?!\.))?(?:[eE][+\-]?\d+)?/),g("number","number");if(t.reAllowed&&"~"==n&&e.eat(/\//))return m(e,"/"),e.eatWhile(/[gimsu]/),g("regexp","string-2");if("/"==n)return e.eat("*")?p(e,t,y):e.eat("/")?(e.skipToEnd(),g("comment","comment")):(e.eatWhile(h),g("operator",null,e.current()));if("#"==n)return e.skipToEnd(),g("conditional","meta");if("@"==n)return e.eat(/:/),e.eatWhile(/[\w_]/),g("metadata","meta");if(h.test(n))return e.eatWhile(h),g("operator",null,e.current());if(/[A-Z]/.test(n))return e.eatWhile(/[\w_<>]/),g("type","variable-3",i=e.current());e.eatWhile(/[\w_]/);var r,i=e.current(),o=d.propertyIsEnumerable(i)&&d[i];return o&&t.kwAllowed?g(o.type,o.style,i):g("variable","variable",i)}function y(e,t){for(var n,r=!1;n=e.next();){if("/"==n&&r){t.tokenize=v;break}r="*"==n}return g("comment","comment")}var b={atom:!0,number:!0,variable:!0,string:!0,regexp:!0};function x(e,t,n,r,i,o){this.indented=e,this.column=t,this.type=n,this.prev=i,this.info=o,null!=r&&(this.align=r)}function w(e,t){for(var n=e.localVars;n;n=n.next)if(n.name==t)return!0}function k(e,t){if(/[a-z]/.test(t.charAt(0)))return!1;for(var n=e.importedtypes.length,r=0;r<n;r++)if(e.importedtypes[r]==t)return!0}function C(e){for(var t=S.state,n=t.importedtypes;n;n=n.next)if(n.name==e)return;t.importedtypes={name:e,next:t.importedtypes}}var S={state:null,column:null,marked:null,cc:null};function T(){for(var e=arguments.length-1;e>=0;e--)S.cc.push(arguments[e])}function L(){return T.apply(null,arguments),!0}function M(e,t){for(var n=t;n;n=n.next)if(n.name==e)return!0;return!1}function O(e){var t=S.state;if(t.context){if(S.marked="def",M(e,t.localVars))return;t.localVars={name:e,next:t.localVars}}else if(t.globalVars){if(M(e,t.globalVars))return;t.globalVars={name:e,next:t.globalVars}}}var N={name:"this",next:null};function A(){S.state.context||(S.state.localVars=N),S.state.context={prev:S.state.context,vars:S.state.localVars}}function E(){S.state.localVars=S.state.context.vars,S.state.context=S.state.context.prev}function z(e,t){var n=function(){var n=S.state;n.lexical=new x(n.indented,S.stream.column(),e,null,n.lexical,t)};return n.lex=!0,n}function P(){var e=S.state;e.lexical.prev&&(")"==e.lexical.type&&(e.indented=e.lexical.indented),e.lexical=e.lexical.prev)}function D(e){return function t(n){return n==e?L():";"==e?T():L(t)}}function I(e){return"@"==e?L(R):"var"==e?L(z("vardef"),X,D(";"),P):"keyword a"==e?L(z("form"),F,I,P):"keyword b"==e?L(z("form"),I,P):"{"==e?L(z("}"),A,G,P,E):";"==e?L():"attribute"==e?L(H):"function"==e?L(J):"for"==e?L(z("form"),D("("),z(")"),Y,D(")"),P,I,P):"variable"==e?L(z("stat"),U):"switch"==e?L(z("form"),F,z("}","switch"),D("{"),G,P,P):"case"==e?L(F,D(":")):"default"==e?L(D(":")):"catch"==e?L(z("form"),A,D("("),re,D(")"),I,P,E):"import"==e?L(j,D(";")):"typedef"==e?L(q):T(z("stat"),F,D(";"),P)}function F(e){return b.hasOwnProperty(e)||"type"==e?L(W):"function"==e?L(J):"keyword c"==e?L(_):"("==e?L(z(")"),_,D(")"),P,W):"operator"==e?L(F):"["==e?L(z("]"),$(_,"]"),P,W):"{"==e?L(z("}"),$(K,"}"),P,W):L()}function _(e){return e.match(/[;\}\)\],]/)?T():T(F)}function W(e,t){return"operator"==e&&/\+\+|--/.test(t)?L(W):"operator"==e||":"==e?L(F):";"!=e?"("==e?L(z(")"),$(F,")"),P,W):"."==e?L(V,W):"["==e?L(z("]"),F,D("]"),P,W):void 0:void 0}function H(e){return"attribute"==e?L(H):"function"==e?L(J):"var"==e?L(X):void 0}function R(e){return":"==e||"variable"==e?L(R):"("==e?L(z(")"),$(B,")"),P,I):void 0}function B(e){if("variable"==e)return L()}function j(e,t){return"variable"==e&&/[A-Z]/.test(t.charAt(0))?(C(t),L()):"variable"==e||"property"==e||"."==e||"*"==t?L(j):void 0}function q(e,t){return"variable"==e&&/[A-Z]/.test(t.charAt(0))?(C(t),L()):"type"==e&&/[A-Z]/.test(t.charAt(0))?L():void 0}function U(e){return":"==e?L(P,I):T(W,D(";"),P)}function V(e){if("variable"==e)return S.marked="property",L()}function K(e){if("variable"==e&&(S.marked="property"),b.hasOwnProperty(e))return L(D(":"),F)}function $(e,t){function n(r){return","==r?L(e,n):r==t?L():L(D(t))}return function(r){return r==t?L():T(e,n)}}function G(e){return"}"==e?L():T(I,G)}function X(e,t){return"variable"==e?(O(t),L(ee,Z)):L()}function Z(e,t){return"="==t?L(F,Z):","==e?L(X):void 0}function Y(e,t){return"variable"==e?(O(t),L(Q,F)):T()}function Q(e,t){if("in"==t)return L()}function J(e,t){return"variable"==e||"type"==e?(O(t),L(J)):"new"==t?L(J):"("==e?L(z(")"),A,$(re,")"),P,ee,I,E):void 0}function ee(e){if(":"==e)return L(te)}function te(e){return"type"==e||"variable"==e?L():"{"==e?L(z("}"),$(ne,"}"),P):void 0}function ne(e){if("variable"==e)return L(ee)}function re(e,t){if("variable"==e)return O(t),L(ee)}return E.lex=!0,P.lex=!0,{startState:function(e){var r={tokenize:v,reAllowed:!0,kwAllowed:!0,cc:[],lexical:new x((e||0)-n,0,"block",!1),localVars:t.localVars,importedtypes:["Int","Float","String","Void","Std","Bool","Dynamic","Array"],context:t.localVars&&{vars:t.localVars},indented:0};return t.globalVars&&"object"==typeof t.globalVars&&(r.globalVars=t.globalVars),r},token:function(e,t){if(e.sol()&&(t.lexical.hasOwnProperty("align")||(t.lexical.align=!1),t.indented=e.indentation()),e.eatSpace())return null;var n=t.tokenize(e,t);return"comment"==f?n:(t.reAllowed=!("operator"!=f&&"keyword c"!=f&&!f.match(/^[\[{}\(,;:]$/)),t.kwAllowed="."!=f,function(e,t,n,r,i){var o=e.cc;for(S.state=e,S.stream=i,S.marked=null,S.cc=o,e.lexical.hasOwnProperty("align")||(e.lexical.align=!0);;)if((o.length?o.pop():I)(n,r)){for(;o.length&&o[o.length-1].lex;)o.pop()();return S.marked?S.marked:"variable"==n&&w(e,r)?"variable-2":"variable"==n&&k(e,r)?"variable-3":t}}(t,n,f,i,e))},indent:function(e,t){if(e.tokenize!=v)return 0;var r=t&&t.charAt(0),i=e.lexical;"stat"==i.type&&"}"==r&&(i=i.prev);var o=i.type,a=r==o;return"vardef"==o?i.indented+4:"form"==o&&"{"==r?i.indented:"stat"==o||"form"==o?i.indented+n:"switch"!=i.info||a?i.align?i.column+(a?0:1):i.indented+(a?0:n):i.indented+(/^(?:case|default)\b/.test(t)?n:2*n)},electricChars:"{}",blockCommentStart:"/*",blockCommentEnd:"*/",lineComment:"//"}})),e.defineMIME("text/x-haxe","haxe"),e.defineMode("hxml",(function(){return{startState:function(){return{define:!1,inString:!1}},token:function(e,t){var n=e.peek(),r=e.sol();if("#"==n)return e.skipToEnd(),"comment";if(r&&"-"==n){var i="variable-2";return e.eat(/-/),"-"==e.peek()&&(e.eat(/-/),i="keyword a"),"D"==e.peek()&&(e.eat(/[D]/),i="keyword c",t.define=!0),e.eatWhile(/[A-Z]/i),i}return n=e.peek(),0==t.inString&&"'"==n&&(t.inString=!0,e.next()),1==t.inString?(e.skipTo("'")||e.skipToEnd(),"'"==e.peek()&&(e.next(),t.inString=!1),"string"):(e.next(),null)},lineComment:"#"}})),e.defineMIME("text/x-hxml","hxml")}(n(0))},function(e,t,n){!function(e){"use strict";e.defineMode("http",(function(){function e(e,t){return e.skipToEnd(),t.cur=a,"error"}function t(t,r){return t.match(/^HTTP\/\d\.\d/)?(r.cur=n,"keyword"):t.match(/^[A-Z]+/)&&/[ \t]/.test(t.peek())?(r.cur=i,"keyword"):e(t,r)}function n(t,n){var i=t.match(/^\d+/);if(!i)return e(t,n);n.cur=r;var o=Number(i[0]);return o>=100&&o<200?"positive informational":o>=200&&o<300?"positive success":o>=300&&o<400?"positive redirect":o>=400&&o<500?"negative client-error":o>=500&&o<600?"negative server-error":"error"}function r(e,t){return e.skipToEnd(),t.cur=a,null}function i(e,t){return e.eatWhile(/\S/),t.cur=o,"string-2"}function o(t,n){return t.match(/^HTTP\/\d\.\d$/)?(n.cur=a,"keyword"):e(t,n)}function a(e){return e.sol()&&!e.eat(/[ \t]/)?e.match(/^.*?:/)?"atom":(e.skipToEnd(),"error"):(e.skipToEnd(),"string")}function l(e){return e.skipToEnd(),null}return{token:function(e,t){var n=t.cur;return n!=a&&n!=l&&e.eatSpace()?null:n(e,t)},blankLine:function(e){e.cur=l},startState:function(){return{cur:t}}}})),e.defineMIME("message/http","http")}(n(0))},function(e,t,n){!function(e){"use strict";var t={script:[["lang",/(javascript|babel)/i,"javascript"],["type",/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i,"javascript"],["type",/./,"text/plain"],[null,null,"javascript"]],style:[["lang",/^css$/i,"css"],["type",/^(text\/)?(x-)?(stylesheet|css)$/i,"css"],["type",/./,"text/plain"],[null,null,"css"]]},n={};function r(e,t){var r=e.match(function(e){var t=n[e];return t||(n[e]=new RegExp("\\s+"+e+"\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*"))}(t));return r?/^\s*(.*?)\s*$/.exec(r[2])[1]:""}function i(e,t){return new RegExp((t?"^":"")+"</s*"+e+"s*>","i")}function o(e,t){for(var n in e)for(var r=t[n]||(t[n]=[]),i=e[n],o=i.length-1;o>=0;o--)r.unshift(i[o])}e.defineMode("htmlmixed",(function(n,a){var l=e.getMode(n,{name:"xml",htmlMode:!0,multilineTagIndentFactor:a.multilineTagIndentFactor,multilineTagIndentPastTag:a.multilineTagIndentPastTag}),s={},c=a&&a.tags,u=a&&a.scriptTypes;if(o(t,s),c&&o(c,s),u)for(var f=u.length-1;f>=0;f--)s.script.unshift(["type",u[f].matches,u[f].mode]);function d(t,o){var a,c=l.token(t,o.htmlState),u=/\btag\b/.test(c);if(u&&!/[<>\s\/]/.test(t.current())&&(a=o.htmlState.tagName&&o.htmlState.tagName.toLowerCase())&&s.hasOwnProperty(a))o.inTag=a+" ";else if(o.inTag&&u&&/>$/.test(t.current())){var f=/^([\S]+) (.*)/.exec(o.inTag);o.inTag=null;var h=">"==t.current()&&function(e,t){for(var n=0;n<e.length;n++){var i=e[n];if(!i[0]||i[1].test(r(t,i[0])))return i[2]}}(s[f[1]],f[2]),p=e.getMode(n,h),m=i(f[1],!0),g=i(f[1],!1);o.token=function(e,t){return e.match(m,!1)?(t.token=d,t.localState=t.localMode=null,null):function(e,t,n){var r=e.current(),i=r.search(t);return i>-1?e.backUp(r.length-i):r.match(/<\/?$/)&&(e.backUp(r.length),e.match(t,!1)||e.match(r)),n}(e,g,t.localMode.token(e,t.localState))},o.localMode=p,o.localState=e.startState(p,l.indent(o.htmlState,"",""))}else o.inTag&&(o.inTag+=t.current(),t.eol()&&(o.inTag+=" "));return c}return{startState:function(){return{token:d,inTag:null,localMode:null,localState:null,htmlState:e.startState(l)}},copyState:function(t){var n;return t.localState&&(n=e.copyState(t.localMode,t.localState)),{token:t.token,inTag:t.inTag,localMode:t.localMode,localState:n,htmlState:e.copyState(l,t.htmlState)}},token:function(e,t){return t.token(e,t)},indent:function(t,n,r){return!t.localMode||/^\s*<\//.test(n)?l.indent(t.htmlState,n,r):t.localMode.indent?t.localMode.indent(t.localState,n,r):e.Pass},innerMode:function(e){return{state:e.localState||e.htmlState,mode:e.localMode||l}}}}),"xml","javascript","css"),e.defineMIME("text/html","htmlmixed")}(n(0),n(3),n(2),n(5))},function(e,t,n){!function(e){"use strict";function t(e,t,n,r){this.state=e,this.mode=t,this.depth=n,this.prev=r}function n(r){return new t(e.copyState(r.mode,r.state),r.mode,r.depth,r.prev&&n(r.prev))}e.defineMode("jsx",(function(r,i){var o=e.getMode(r,{name:"xml",allowMissing:!0,multilineTagIndentPastTag:!1,allowMissingTagName:!0}),a=e.getMode(r,i&&i.base||"javascript");function l(e){var t=e.tagName;e.tagName=null;var n=o.indent(e,"","");return e.tagName=t,n}function s(n,i){return i.context.mode==o?function(n,i,c){if(2==c.depth)return n.match(/^.*?\*\//)?c.depth=1:n.skipToEnd(),"comment";if("{"==n.peek()){o.skipAttribute(c.state);var u=l(c.state),f=c.state.context;if(f&&n.match(/^[^>]*>\s*$/,!1)){for(;f.prev&&!f.startOfLine;)f=f.prev;f.startOfLine?u-=r.indentUnit:c.prev.state.lexical&&(u=c.prev.state.lexical.indented)}else 1==c.depth&&(u+=r.indentUnit);return i.context=new t(e.startState(a,u),a,0,i.context),null}if(1==c.depth){if("<"==n.peek())return o.skipAttribute(c.state),i.context=new t(e.startState(o,l(c.state)),o,0,i.context),null;if(n.match("//"))return n.skipToEnd(),"comment";if(n.match("/*"))return c.depth=2,s(n,i)}var d,h=o.token(n,c.state),p=n.current();return/\btag\b/.test(h)?/>$/.test(p)?c.state.context?c.depth=0:i.context=i.context.prev:/^</.test(p)&&(c.depth=1):!h&&(d=p.indexOf("{"))>-1&&n.backUp(p.length-d),h}(n,i,i.context):function(n,r,i){if("<"==n.peek()&&a.expressionAllowed(n,i.state))return a.skipExpression(i.state),r.context=new t(e.startState(o,a.indent(i.state,"","")),o,0,r.context),null;var l=a.token(n,i.state);if(!l&&null!=i.depth){var s=n.current();"{"==s?i.depth++:"}"==s&&0==--i.depth&&(r.context=r.context.prev)}return l}(n,i,i.context)}return{startState:function(){return{context:new t(e.startState(a),a)}},copyState:function(e){return{context:n(e.context)}},token:s,indent:function(e,t,n){return e.context.mode.indent(e.context.state,t,n)},innerMode:function(e){return e.context}}}),"xml","javascript"),e.defineMIME("text/jsx","jsx"),e.defineMIME("text/typescript-jsx",{name:"jsx",base:{name:"javascript",typescript:!0}})}(n(0),n(3),n(2))},function(e,t,n){!function(e){"use strict";e.defineMode("coffeescript",(function(e,t){function n(e){return new RegExp("^(("+e.join(")|(")+"))\\b")}var r=/^(?:->|=>|\+[+=]?|-[\-=]?|\*[\*=]?|\/[\/=]?|[=!]=|<[><]?=?|>>?=?|%=?|&=?|\|=?|\^=?|\~|!|\?|(or|and|\|\||&&|\?)=)/,i=/^(?:[()\[\]{},:`=;]|\.\.?\.?)/,o=/^[_A-Za-z$][_A-Za-z$0-9]*/,a=/^@[_A-Za-z$][_A-Za-z$0-9]*/,l=n(["and","or","not","is","isnt","in","instanceof","typeof"]),s=["for","while","loop","if","unless","else","switch","try","catch","finally","class"],c=n(s.concat(["break","by","continue","debugger","delete","do","in","of","new","return","then","this","@","throw","when","until","extends"]));s=n(s);var u=/^('{3}|\"{3}|['\"])/,f=/^(\/{3}|\/)/,d=n(["Infinity","NaN","undefined","null","true","false","on","off","yes","no"]);function h(e,t){if(e.sol()){null===t.scope.align&&(t.scope.align=!1);var n=t.scope.offset;if(e.eatSpace()){var s=e.indentation();return s>n&&"coffee"==t.scope.type?"indent":s<n?"dedent":null}n>0&&v(e,t)}if(e.eatSpace())return null;var h=e.peek();if(e.match("####"))return e.skipToEnd(),"comment";if(e.match("###"))return t.tokenize=m,t.tokenize(e,t);if("#"===h)return e.skipToEnd(),"comment";if(e.match(/^-?[0-9\.]/,!1)){var g=!1;if(e.match(/^-?\d*\.\d+(e[\+\-]?\d+)?/i)&&(g=!0),e.match(/^-?\d+\.\d*/)&&(g=!0),e.match(/^-?\.\d+/)&&(g=!0),g)return"."==e.peek()&&e.backUp(1),"number";var y=!1;if(e.match(/^-?0x[0-9a-f]+/i)&&(y=!0),e.match(/^-?[1-9]\d*(e[\+\-]?\d+)?/)&&(y=!0),e.match(/^-?0(?![\dx])/i)&&(y=!0),y)return"number"}if(e.match(u))return t.tokenize=p(e.current(),!1,"string"),t.tokenize(e,t);if(e.match(f)){if("/"!=e.current()||e.match(/^.*\//,!1))return t.tokenize=p(e.current(),!0,"string-2"),t.tokenize(e,t);e.backUp(1)}return e.match(r)||e.match(l)?"operator":e.match(i)?"punctuation":e.match(d)?"atom":e.match(a)||t.prop&&e.match(o)?"property":e.match(c)?"keyword":e.match(o)?"variable":(e.next(),"error")}function p(e,n,r){return function(i,o){for(;!i.eol();)if(i.eatWhile(/[^'"\/\\]/),i.eat("\\")){if(i.next(),n&&i.eol())return r}else{if(i.match(e))return o.tokenize=h,r;i.eat(/['"\/]/)}return n&&(t.singleLineStringErrors?r="error":o.tokenize=h),r}}function m(e,t){for(;!e.eol();){if(e.eatWhile(/[^#]/),e.match("###")){t.tokenize=h;break}e.eatWhile("#")}return"comment"}function g(t,n,r){r=r||"coffee";for(var i=0,o=!1,a=null,l=n.scope;l;l=l.prev)if("coffee"===l.type||"}"==l.type){i=l.offset+e.indentUnit;break}"coffee"!==r?(o=null,a=t.column()+t.current().length):n.scope.align&&(n.scope.align=!1),n.scope={offset:i,type:r,prev:n.scope,align:o,alignOffset:a}}function v(e,t){if(t.scope.prev){if("coffee"===t.scope.type){for(var n=e.indentation(),r=!1,i=t.scope;i;i=i.prev)if(n===i.offset){r=!0;break}if(!r)return!0;for(;t.scope.prev&&t.scope.offset!==n;)t.scope=t.scope.prev;return!1}return t.scope=t.scope.prev,!1}}return{startState:function(e){return{tokenize:h,scope:{offset:e||0,type:"coffee",prev:null,align:!1},prop:!1,dedent:0}},token:function(e,t){var n=null===t.scope.align&&t.scope;n&&e.sol()&&(n.align=!1);var r=function(e,t){var n=t.tokenize(e,t),r=e.current();"return"===r&&(t.dedent=!0),(("->"===r||"=>"===r)&&e.eol()||"indent"===n)&&g(e,t);var i="[({".indexOf(r);if(-1!==i&&g(e,t,"])}".slice(i,i+1)),s.exec(r)&&g(e,t),"then"==r&&v(e,t),"dedent"===n&&v(e,t))return"error";if(-1!==(i="])}".indexOf(r))){for(;"coffee"==t.scope.type&&t.scope.prev;)t.scope=t.scope.prev;t.scope.type==r&&(t.scope=t.scope.prev)}return t.dedent&&e.eol()&&("coffee"==t.scope.type&&t.scope.prev&&(t.scope=t.scope.prev),t.dedent=!1),n}(e,t);return r&&"comment"!=r&&(n&&(n.align=!0),t.prop="punctuation"==r&&"."==e.current()),r},indent:function(e,t){if(e.tokenize!=h)return 0;var n=e.scope,r=t&&"])}".indexOf(t.charAt(0))>-1;if(r)for(;"coffee"==n.type&&n.prev;)n=n.prev;var i=r&&n.type===t.charAt(0);return n.align?n.alignOffset-(i?1:0):(i?n.prev:n).offset},lineComment:"#",fold:"indent"}})),e.defineMIME("application/vnd.coffeescript","coffeescript"),e.defineMIME("text/x-coffeescript","coffeescript"),e.defineMIME("text/coffeescript","coffeescript")}(n(0))},function(e,t,n){!function(e){"use strict";e.defineMode("elm",(function(){function e(e,t,n){return t(n),n(e,t)}var t=/[a-z_]/,n=/[A-Z]/,r=/[0-9]/,i=/[0-9A-Fa-f]/,o=/[0-7]/,a=/[a-z_A-Z0-9\']/,l=/[-!#$%&*+.\/<=>?@\\^|~:\u03BB\u2192]/,s=/[(),;[\]`{}]/,c=/[ \t\v\f]/;function u(){return function(d,h){if(d.eatWhile(c))return null;var p=d.next();if(s.test(p)){if("{"==p&&d.eat("-")){var m="comment";return d.eat("#")&&(m="meta"),e(d,h,function e(t,n){return 0==n?u():function(r,i){for(var o=n;!r.eol();){var a=r.next();if("{"==a&&r.eat("-"))++o;else if("-"==a&&r.eat("}")&&0==--o)return i(u()),t}return i(e(t,o)),t}}(m,1))}return null}if("'"==p)return d.eat("\\"),d.next(),d.eat("'")?"string":"error";if('"'==p)return e(d,h,f);if(n.test(p))return d.eatWhile(a),d.eat(".")?"qualifier":"variable-2";if(t.test(p)){var g=1===d.pos;return d.eatWhile(a),g?"type":"variable"}if(r.test(p)){if("0"==p){if(d.eat(/[xX]/))return d.eatWhile(i),"integer";if(d.eat(/[oO]/))return d.eatWhile(o),"number"}return d.eatWhile(r),m="number",d.eat(".")&&(m="number",d.eatWhile(r)),d.eat(/[eE]/)&&(m="number",d.eat(/[-+]/),d.eatWhile(r)),m}return l.test(p)?"-"==p&&d.eat(/-/)&&(d.eatWhile(/-/),!d.eat(l))?(d.skipToEnd(),"comment"):(d.eatWhile(l),"builtin"):"error"}}function f(e,t){for(;!e.eol();){var n=e.next();if('"'==n)return t(u()),"string";if("\\"==n){if(e.eol()||e.eat(c))return t(d),"string";e.eat("&")||e.next()}}return t(u()),"error"}function d(t,n){return t.eat("\\")?e(t,n,f):(t.next(),n(u()),"error")}var h=function(){for(var e={},t=["case","of","as","if","then","else","let","in","infix","infixl","infixr","type","alias","input","output","foreign","loopback","module","where","import","exposing","_","..","|",":","=","\\",'"',"->","<-"],n=t.length;n--;)e[t[n]]="keyword";return e}();return{startState:function(){return{f:u()}},copyState:function(e){return{f:e.f}},token:function(e,t){var n=t.f(e,(function(e){t.f=e})),r=e.current();return h.hasOwnProperty(r)?h[r]:n}}})),e.defineMIME("text/x-elm","elm")}(n(0))},function(e,t,n){!function(e){"use strict";function t(e,t,n,r,i,o){this.indented=e,this.column=t,this.type=n,this.info=r,this.align=i,this.prev=o}function n(e,n,r,i){var o=e.indented;return e.context&&"statement"==e.context.type&&"statement"!=r&&(o=e.context.indented),e.context=new t(o,n,r,i,null,e.context)}function r(e){var t=e.context.type;return")"!=t&&"]"!=t&&"}"!=t||(e.indented=e.context.indented),e.context=e.context.prev}function i(e,t,n){return"variable"==t.prevToken||"type"==t.prevToken||!!/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(e.string.slice(0,n))||!(!t.typeAtEndOfLine||e.column()!=e.indentation())||void 0}function o(e){for(;;){if(!e||"top"==e.type)return!0;if("}"==e.type&&"namespace"!=e.prev.info)return!1;e=e.prev}}function a(e){for(var t={},n=e.split(" "),r=0;r<n.length;++r)t[n[r]]=!0;return t}function l(e,t){return"function"==typeof e?e(t):e.propertyIsEnumerable(t)}e.defineMode("clike",(function(a,s){var c,u,f=a.indentUnit,d=s.statementIndentUnit||f,h=s.dontAlignCalls,p=s.keywords||{},m=s.types||{},g=s.builtin||{},v=s.blockKeywords||{},y=s.defKeywords||{},b=s.atoms||{},x=s.hooks||{},w=s.multiLineStrings,k=!1!==s.indentStatements,C=!1!==s.indentSwitch,S=s.namespaceSeparator,T=s.isPunctuationChar||/[\[\]{}\(\),;\:\.]/,L=s.numberStart||/[\d\.]/,M=s.number||/^(?:0x[a-f\d]+|0b[01]+|(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)(u|ll?|l|f)?/i,O=s.isOperatorChar||/[+\-*&%=<>!?|\/]/,N=s.isIdentifierChar||/[\w\$_\xa1-\uffff]/,A=s.isReservedIdentifier||!1;function E(e,t){var n,r=e.next();if(x[r]){var i=x[r](e,t);if(!1!==i)return i}if('"'==r||"'"==r)return t.tokenize=(n=r,function(e,t){for(var r,i=!1,o=!1;null!=(r=e.next());){if(r==n&&!i){o=!0;break}i=!i&&"\\"==r}return(o||!i&&!w)&&(t.tokenize=null),"string"}),t.tokenize(e,t);if(T.test(r))return c=r,null;if(L.test(r)){if(e.backUp(1),e.match(M))return"number";e.next()}if("/"==r){if(e.eat("*"))return t.tokenize=z,z(e,t);if(e.eat("/"))return e.skipToEnd(),"comment"}if(O.test(r)){for(;!e.match(/^\/[\/*]/,!1)&&e.eat(O););return"operator"}if(e.eatWhile(N),S)for(;e.match(S);)e.eatWhile(N);var o=e.current();return l(p,o)?(l(v,o)&&(c="newstatement"),l(y,o)&&(u=!0),"keyword"):l(m,o)?"type":l(g,o)||A&&A(o)?(l(v,o)&&(c="newstatement"),"builtin"):l(b,o)?"atom":"variable"}function z(e,t){for(var n,r=!1;n=e.next();){if("/"==n&&r){t.tokenize=null;break}r="*"==n}return"comment"}function P(e,t){s.typeFirstDefinitions&&e.eol()&&o(t.context)&&(t.typeAtEndOfLine=i(e,t,e.pos))}return{startState:function(e){return{tokenize:null,context:new t((e||0)-f,0,"top",null,!1),indented:0,startOfLine:!0,prevToken:null}},token:function(e,t){var a=t.context;if(e.sol()&&(null==a.align&&(a.align=!1),t.indented=e.indentation(),t.startOfLine=!0),e.eatSpace())return P(e,t),null;c=u=null;var l=(t.tokenize||E)(e,t);if("comment"==l||"meta"==l)return l;if(null==a.align&&(a.align=!0),";"==c||":"==c||","==c&&e.match(/^\s*(?:\/\/.*)?$/,!1))for(;"statement"==t.context.type;)r(t);else if("{"==c)n(t,e.column(),"}");else if("["==c)n(t,e.column(),"]");else if("("==c)n(t,e.column(),")");else if("}"==c){for(;"statement"==a.type;)a=r(t);for("}"==a.type&&(a=r(t));"statement"==a.type;)a=r(t)}else c==a.type?r(t):k&&(("}"==a.type||"top"==a.type)&&";"!=c||"statement"==a.type&&"newstatement"==c)&&n(t,e.column(),"statement",e.current());if("variable"==l&&("def"==t.prevToken||s.typeFirstDefinitions&&i(e,t,e.start)&&o(t.context)&&e.match(/^\s*\(/,!1))&&(l="def"),x.token){var f=x.token(e,t,l);void 0!==f&&(l=f)}return"def"==l&&!1===s.styleDefs&&(l="variable"),t.startOfLine=!1,t.prevToken=u?"def":l||c,P(e,t),l},indent:function(t,n){if(t.tokenize!=E&&null!=t.tokenize||t.typeAtEndOfLine)return e.Pass;var r=t.context,i=n&&n.charAt(0),o=i==r.type;if("statement"==r.type&&"}"==i&&(r=r.prev),s.dontIndentStatements)for(;"statement"==r.type&&s.dontIndentStatements.test(r.info);)r=r.prev;if(x.indent){var a=x.indent(t,r,n,f);if("number"==typeof a)return a}var l=r.prev&&"switch"==r.prev.info;if(s.allmanIndentation&&/[{(]/.test(i)){for(;"top"!=r.type&&"}"!=r.type;)r=r.prev;return r.indented}return"statement"==r.type?r.indented+("{"==i?0:d):!r.align||h&&")"==r.type?")"!=r.type||o?r.indented+(o?0:f)+(o||!l||/^(?:case|default)\b/.test(n)?0:f):r.indented+d:r.column+(o?0:1)},electricInput:C?/^\s*(?:case .*?:|default:|\{\}?|\})$/:/^\s*[{}]$/,blockCommentStart:"/*",blockCommentEnd:"*/",blockCommentContinue:" * ",lineComment:"//",fold:"brace"}}));var s="auto if break case register continue return default do sizeof static else struct switch extern typedef union for goto while enum const volatile inline restrict asm fortran",c=a("int long char short double float unsigned signed void bool"),u=a("SEL instancetype id Class Protocol BOOL");function f(e){return l(c,e)||/.+_t$/.test(e)}var d="case do else for if switch while struct enum union";function h(e,t){if(!t.startOfLine)return!1;for(var n,r=null;n=e.peek();){if("\\"==n&&e.match(/^.$/)){r=h;break}if("/"==n&&e.match(/^\/[\/\*]/,!1))break;e.next()}return t.tokenize=r,"meta"}function p(e,t){return"type"==t.prevToken&&"type"}function m(e){return!(!e||e.length<2||"_"!=e[0]||"_"!=e[1]&&e[1]===e[1].toLowerCase())}function g(e){return e.eatWhile(/[\w\.']/),"number"}function v(e,t){if(e.backUp(1),e.match(/(R|u8R|uR|UR|LR)/)){var n=e.match(/"([^\s\\()]{0,16})\(/);return!!n&&(t.cpp11RawStringDelim=n[1],t.tokenize=b,b(e,t))}return e.match(/(u8|u|U|L)/)?!!e.match(/["']/,!1)&&"string":(e.next(),!1)}function y(e,t){for(var n;null!=(n=e.next());)if('"'==n&&!e.eat('"')){t.tokenize=null;break}return"string"}function b(e,t){var n=t.cpp11RawStringDelim.replace(/[^\w\s]/g,"\\$&");return e.match(new RegExp(".*?\\)"+n+'"'))?t.tokenize=null:e.skipToEnd(),"string"}function x(t,n){"string"==typeof t&&(t=[t]);var r=[];function i(e){if(e)for(var t in e)e.hasOwnProperty(t)&&r.push(t)}i(n.keywords),i(n.types),i(n.builtin),i(n.atoms),r.length&&(n.helperType=t[0],e.registerHelper("hintWords",t[0],r));for(var o=0;o<t.length;++o)e.defineMIME(t[o],n)}function w(e,t){for(var n=!1;!e.eol();){if(!n&&e.match('"""')){t.tokenize=null;break}n="\\"==e.next()&&!n}return"string"}function k(e){return function(t,n){for(var r;r=t.next();){if("*"==r&&t.eat("/")){if(1==e){n.tokenize=null;break}return n.tokenize=k(e-1),n.tokenize(t,n)}if("/"==r&&t.eat("*"))return n.tokenize=k(e+1),n.tokenize(t,n)}return"comment"}}x(["text/x-csrc","text/x-c","text/x-chdr"],{name:"clike",keywords:a(s),types:f,blockKeywords:a(d),defKeywords:a("struct enum union"),typeFirstDefinitions:!0,atoms:a("NULL true false"),isReservedIdentifier:m,hooks:{"#":h,"*":p},modeProps:{fold:["brace","include"]}}),x(["text/x-c++src","text/x-c++hdr"],{name:"clike",keywords:a(s+"alignas alignof and and_eq audit axiom bitand bitor catch class compl concept constexpr const_cast decltype delete dynamic_cast explicit export final friend import module mutable namespace new noexcept not not_eq operator or or_eq override private protected public reinterpret_cast requires static_assert static_cast template this thread_local throw try typeid typename using virtual xor xor_eq"),types:f,blockKeywords:a(d+" class try catch"),defKeywords:a("struct enum union class namespace"),typeFirstDefinitions:!0,atoms:a("true false NULL nullptr"),dontIndentStatements:/^template$/,isIdentifierChar:/[\w\$_~\xa1-\uffff]/,isReservedIdentifier:m,hooks:{"#":h,"*":p,u:v,U:v,L:v,R:v,0:g,1:g,2:g,3:g,4:g,5:g,6:g,7:g,8:g,9:g,token:function(e,t,n){if("variable"==n&&"("==e.peek()&&(";"==t.prevToken||null==t.prevToken||"}"==t.prevToken)&&(r=e.current(),(i=/(\w+)::~?(\w+)$/.exec(r))&&i[1]==i[2]))return"def";var r,i}},namespaceSeparator:"::",modeProps:{fold:["brace","include"]}}),x("text/x-java",{name:"clike",keywords:a("abstract assert break case catch class const continue default do else enum extends final finally for goto if implements import instanceof interface native new package private protected public return static strictfp super switch synchronized this throw throws transient try volatile while @interface"),types:a("byte short int long float double boolean char void Boolean Byte Character Double Float Integer Long Number Object Short String StringBuffer StringBuilder Void"),blockKeywords:a("catch class do else finally for if switch try while"),defKeywords:a("class interface enum @interface"),typeFirstDefinitions:!0,atoms:a("true false null"),number:/^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+\.?\d*|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i,hooks:{"@":function(e){return!e.match("interface",!1)&&(e.eatWhile(/[\w\$_]/),"meta")}},modeProps:{fold:["brace","import"]}}),x("text/x-csharp",{name:"clike",keywords:a("abstract as async await base break case catch checked class const continue default delegate do else enum event explicit extern finally fixed for foreach goto if implicit in interface internal is lock namespace new operator out override params private protected public readonly ref return sealed sizeof stackalloc static struct switch this throw try typeof unchecked unsafe using virtual void volatile while add alias ascending descending dynamic from get global group into join let orderby partial remove select set value var yield"),types:a("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32 UInt64 bool byte char decimal double short int long object sbyte float string ushort uint ulong"),blockKeywords:a("catch class do else finally for foreach if struct switch try while"),defKeywords:a("class interface namespace struct var"),typeFirstDefinitions:!0,atoms:a("true false null"),hooks:{"@":function(e,t){return e.eat('"')?(t.tokenize=y,y(e,t)):(e.eatWhile(/[\w\$_]/),"meta")}}}),x("text/x-scala",{name:"clike",keywords:a("abstract case catch class def do else extends final finally for forSome if implicit import lazy match new null object override package private protected return sealed super this throw trait try type val var while with yield _ assert assume require print println printf readLine readBoolean readByte readShort readChar readInt readLong readFloat readDouble"),types:a("AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either Enumeration Equiv Error Exception Fractional Function IndexedSeq Int Integral Iterable Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable Compiler Double Exception Float Integer Long Math Number Object Package Pair Process Runtime Runnable SecurityManager Short StackTraceElement StrictMath String StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"),multiLineStrings:!0,blockKeywords:a("catch class enum do else finally for forSome if match switch try while"),defKeywords:a("class enum def object package trait type val var"),atoms:a("true false null"),indentStatements:!1,indentSwitch:!1,isOperatorChar:/[+\-*&%=<>!?|\/#:@]/,hooks:{"@":function(e){return e.eatWhile(/[\w\$_]/),"meta"},'"':function(e,t){return!!e.match('""')&&(t.tokenize=w,t.tokenize(e,t))},"'":function(e){return e.eatWhile(/[\w\$_\xa1-\uffff]/),"atom"},"=":function(e,n){var r=n.context;return!("}"!=r.type||!r.align||!e.eat(">"))&&(n.context=new t(r.indented,r.column,r.type,r.info,null,r.prev),"operator")},"/":function(e,t){return!!e.eat("*")&&(t.tokenize=k(1),t.tokenize(e,t))}},modeProps:{closeBrackets:{pairs:'()[]{}""',triples:'"'}}}),x("text/x-kotlin",{name:"clike",keywords:a("package as typealias class interface this super val operator var fun for is in This throw return annotation break continue object if else while do try when !in !is as? file import where by get set abstract enum open inner override private public internal protected catch finally out final vararg reified dynamic companion constructor init sealed field property receiver param sparam lateinit data inline noinline tailrec external annotation crossinline const operator infix suspend actual expect setparam"),types:a("Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable Compiler Double Exception Float Integer Long Math Number Object Package Pair Process Runtime Runnable SecurityManager Short StackTraceElement StrictMath String StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void Annotation Any BooleanArray ByteArray Char CharArray DeprecationLevel DoubleArray Enum FloatArray Function Int IntArray Lazy LazyThreadSafetyMode LongArray Nothing ShortArray Unit"),intendSwitch:!1,indentStatements:!1,multiLineStrings:!0,number:/^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+(\.\d+)?|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i,blockKeywords:a("catch class do else finally for if where try while enum"),defKeywords:a("class val var object interface fun"),atoms:a("true false null this"),hooks:{"@":function(e){return e.eatWhile(/[\w\$_]/),"meta"},"*":function(e,t){return"."==t.prevToken?"variable":"operator"},'"':function(e,t){var n;return t.tokenize=(n=e.match('""'),function(e,t){for(var r,i=!1,o=!1;!e.eol();){if(!n&&!i&&e.match('"')){o=!0;break}if(n&&e.match('"""')){o=!0;break}r=e.next(),!i&&"$"==r&&e.match("{")&&e.skipTo("}"),i=!i&&"\\"==r&&!n}return!o&&n||(t.tokenize=null),"string"}),t.tokenize(e,t)},"/":function(e,t){return!!e.eat("*")&&(t.tokenize=k(1),t.tokenize(e,t))},indent:function(e,t,n,r){var i=n&&n.charAt(0);return"}"!=e.prevToken&&")"!=e.prevToken||""!=n?"operator"==e.prevToken&&"}"!=n&&"}"!=e.context.type||"variable"==e.prevToken&&"."==i||("}"==e.prevToken||")"==e.prevToken)&&"."==i?2*r+t.indented:t.align&&"}"==t.type?t.indented+(e.context.type==(n||"").charAt(0)?0:r):void 0:e.indented}},modeProps:{closeBrackets:{triples:'"'}}}),x(["x-shader/x-vertex","x-shader/x-fragment"],{name:"clike",keywords:a("sampler1D sampler2D sampler3D samplerCube sampler1DShadow sampler2DShadow const attribute uniform varying break continue discard return for while do if else struct in out inout"),types:a("float int bool void vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 mat2 mat3 mat4"),blockKeywords:a("for while do if else struct"),builtin:a("radians degrees sin cos tan asin acos atan pow exp log exp2 sqrt inversesqrt abs sign floor ceil fract mod min max clamp mix step smoothstep length distance dot cross normalize ftransform faceforward reflect refract matrixCompMult lessThan lessThanEqual greaterThan greaterThanEqual equal notEqual any all not texture1D texture1DProj texture1DLod texture1DProjLod texture2D texture2DProj texture2DLod texture2DProjLod texture3D texture3DProj texture3DLod texture3DProjLod textureCube textureCubeLod shadow1D shadow2D shadow1DProj shadow2DProj shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod dFdx dFdy fwidth noise1 noise2 noise3 noise4"),atoms:a("true false gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 gl_FogCoord gl_PointCoord gl_Position gl_PointSize gl_ClipVertex gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor gl_TexCoord gl_FogFragCoord gl_FragCoord gl_FrontFacing gl_FragData gl_FragDepth gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose gl_ProjectionMatrixInverseTranspose gl_ModelViewProjectionMatrixInverseTranspose gl_TextureMatrixInverseTranspose gl_NormalScale gl_DepthRange gl_ClipPlane gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel gl_FrontLightModelProduct gl_BackLightModelProduct gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ gl_FogParameters gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits gl_MaxDrawBuffers"),indentSwitch:!1,hooks:{"#":h},modeProps:{fold:["brace","include"]}}),x("text/x-nesc",{name:"clike",keywords:a(s+" as atomic async call command component components configuration event generic implementation includes interface module new norace nx_struct nx_union post provides signal task uses abstract extends"),types:f,blockKeywords:a(d),atoms:a("null true false"),hooks:{"#":h},modeProps:{fold:["brace","include"]}}),x("text/x-objectivec",{name:"clike",keywords:a(s+" bycopy byref in inout oneway out self super atomic nonatomic retain copy readwrite readonly strong weak assign typeof nullable nonnull null_resettable _cmd @interface @implementation @end @protocol @encode @property @synthesize @dynamic @class @public @package @private @protected @required @optional @try @catch @finally @import @selector @encode @defs @synchronized @autoreleasepool @compatibility_alias @available"),types:function(e){return f(e)||l(u,e)},builtin:a("FOUNDATION_EXPORT FOUNDATION_EXTERN NS_INLINE NS_FORMAT_FUNCTION NS_RETURNS_RETAINED NS_ERROR_ENUM NS_RETURNS_NOT_RETAINED NS_RETURNS_INNER_POINTER NS_DESIGNATED_INITIALIZER NS_ENUM NS_OPTIONS NS_REQUIRES_NIL_TERMINATION NS_ASSUME_NONNULL_BEGIN NS_ASSUME_NONNULL_END NS_SWIFT_NAME NS_REFINED_FOR_SWIFT"),blockKeywords:a(d+" @synthesize @try @catch @finally @autoreleasepool @synchronized"),defKeywords:a("struct enum union @interface @implementation @protocol @class"),dontIndentStatements:/^@.*$/,typeFirstDefinitions:!0,atoms:a("YES NO NULL Nil nil true false nullptr"),isReservedIdentifier:m,hooks:{"#":h,"*":p},modeProps:{fold:["brace","include"]}}),x("text/x-squirrel",{name:"clike",keywords:a("base break clone continue const default delete enum extends function in class foreach local resume return this throw typeof yield constructor instanceof static"),types:f,blockKeywords:a("case catch class else for foreach if switch try while"),defKeywords:a("function local class"),typeFirstDefinitions:!0,atoms:a("true false null"),hooks:{"#":h},modeProps:{fold:["brace","include"]}});var C=null;x("text/x-ceylon",{name:"clike",keywords:a("abstracts alias assembly assert assign break case catch class continue dynamic else exists extends finally for function given if import in interface is let module new nonempty object of out outer package return satisfies super switch then this throw try value void while"),types:function(e){var t=e.charAt(0);return t===t.toUpperCase()&&t!==t.toLowerCase()},blockKeywords:a("case catch class dynamic else finally for function if interface module new object switch try while"),defKeywords:a("class dynamic function interface module object package value"),builtin:a("abstract actual aliased annotation by default deprecated doc final formal late license native optional sealed see serializable shared suppressWarnings tagged throws variable"),isPunctuationChar:/[\[\]{}\(\),;\:\.`]/,isOperatorChar:/[+\-*&%=<>!?|^~:\/]/,numberStart:/[\d#$]/,number:/^(?:#[\da-fA-F_]+|\$[01_]+|[\d_]+[kMGTPmunpf]?|[\d_]+\.[\d_]+(?:[eE][-+]?\d+|[kMGTPmunpf]|)|)/i,multiLineStrings:!0,typeFirstDefinitions:!0,atoms:a("true false null larger smaller equal empty finished"),indentSwitch:!1,styleDefs:!1,hooks:{"@":function(e){return e.eatWhile(/[\w\$_]/),"meta"},'"':function(e,t){return t.tokenize=function e(t){return function(n,r){for(var i,o=!1,a=!1;!n.eol();){if(!o&&n.match('"')&&("single"==t||n.match('""'))){a=!0;break}if(!o&&n.match("``")){C=e(t),a=!0;break}i=n.next(),o="single"==t&&!o&&"\\"==i}return a&&(r.tokenize=null),"string"}}(e.match('""')?"triple":"single"),t.tokenize(e,t)},"`":function(e,t){return!(!C||!e.match("`"))&&(t.tokenize=C,C=null,t.tokenize(e,t))},"'":function(e){return e.eatWhile(/[\w\$_\xa1-\uffff]/),"atom"},token:function(e,t,n){if(("variable"==n||"type"==n)&&"."==t.prevToken)return"variable-2"}},modeProps:{fold:["brace","import"],closeBrackets:{triples:'"'}}})}(n(0))},function(e,t,n){!function(e){"use strict";e.defineSimpleMode("rust",{start:[{regex:/b?"/,token:"string",next:"string"},{regex:/b?r"/,token:"string",next:"string_raw"},{regex:/b?r#+"/,token:"string",next:"string_raw_hash"},{regex:/'(?:[^'\\]|\\(?:[nrt0'"]|x[\da-fA-F]{2}|u\{[\da-fA-F]{6}\}))'/,token:"string-2"},{regex:/b'(?:[^']|\\(?:['\\nrt0]|x[\da-fA-F]{2}))'/,token:"string-2"},{regex:/(?:(?:[0-9][0-9_]*)(?:(?:[Ee][+-]?[0-9_]+)|\.[0-9_]+(?:[Ee][+-]?[0-9_]+)?)(?:f32|f64)?)|(?:0(?:b[01_]+|(?:o[0-7_]+)|(?:x[0-9a-fA-F_]+))|(?:[0-9][0-9_]*))(?:u8|u16|u32|u64|i8|i16|i32|i64|isize|usize)?/,token:"number"},{regex:/(let(?:\s+mut)?|fn|enum|mod|struct|type)(\s+)([a-zA-Z_][a-zA-Z0-9_]*)/,token:["keyword",null,"def"]},{regex:/(?:abstract|alignof|as|box|break|continue|const|crate|do|else|enum|extern|fn|for|final|if|impl|in|loop|macro|match|mod|move|offsetof|override|priv|proc|pub|pure|ref|return|self|sizeof|static|struct|super|trait|type|typeof|unsafe|unsized|use|virtual|where|while|yield)\b/,token:"keyword"},{regex:/\b(?:Self|isize|usize|char|bool|u8|u16|u32|u64|f16|f32|f64|i8|i16|i32|i64|str|Option)\b/,token:"atom"},{regex:/\b(?:true|false|Some|None|Ok|Err)\b/,token:"builtin"},{regex:/\b(fn)(\s+)([a-zA-Z_][a-zA-Z0-9_]*)/,token:["keyword",null,"def"]},{regex:/#!?\[.*\]/,token:"meta"},{regex:/\/\/.*/,token:"comment"},{regex:/\/\*/,token:"comment",next:"comment"},{regex:/[-+\/*=<>!]+/,token:"operator"},{regex:/[a-zA-Z_]\w*!/,token:"variable-3"},{regex:/[a-zA-Z_]\w*/,token:"variable"},{regex:/[\{\[\(]/,indent:!0},{regex:/[\}\]\)]/,dedent:!0}],string:[{regex:/"/,token:"string",next:"start"},{regex:/(?:[^\\"]|\\(?:.|$))*/,token:"string"}],string_raw:[{regex:/"/,token:"string",next:"start"},{regex:/[^"]*/,token:"string"}],string_raw_hash:[{regex:/"#+/,token:"string",next:"start"},{regex:/(?:[^"]|"(?!#))*/,token:"string"}],comment:[{regex:/.*?\*\//,token:"comment",next:"start"},{regex:/.*/,token:"comment"}],meta:{dontIndentStates:["comment"],electricInput:/^\s*\}$/,blockCommentStart:"/*",blockCommentEnd:"*/",lineComment:"//",fold:"brace"}}),e.defineMIME("text/x-rustsrc","rust"),e.defineMIME("text/rust","rust")}(n(0),n(25))},function(e,t,n){!function(e){"use strict";function t(e,t){if(!e.hasOwnProperty(t))throw new Error("Undefined state "+t+" in simple mode")}function n(e,t){if(!e)return/(?:)/;var n="";return e instanceof RegExp?(e.ignoreCase&&(n="i"),e=e.source):e=String(e),new RegExp((!1===t?"":"^")+"(?:"+e+")",n)}function r(e,r){(e.next||e.push)&&t(r,e.next||e.push),this.regex=n(e.regex),this.token=function(e){if(!e)return null;if(e.apply)return e;if("string"==typeof e)return e.replace(/\./g," ");for(var t=[],n=0;n<e.length;n++)t.push(e[n]&&e[n].replace(/\./g," "));return t}(e.token),this.data=e}function i(e,t){return function(n,r){if(r.pending){var i=r.pending.shift();return 0==r.pending.length&&(r.pending=null),n.pos+=i.text.length,i.token}if(r.local){if(r.local.end&&n.match(r.local.end)){var o=r.local.endToken||null;return r.local=r.localState=null,o}var l;return o=r.local.mode.token(n,r.localState),r.local.endScan&&(l=r.local.endScan.exec(n.current()))&&(n.pos=n.start+l.index),o}for(var s=e[r.state],c=0;c<s.length;c++){var u=s[c],f=(!u.data.sol||n.sol())&&n.match(u.regex);if(f){u.data.next?r.state=u.data.next:u.data.push?((r.stack||(r.stack=[])).push(r.state),r.state=u.data.push):u.data.pop&&r.stack&&r.stack.length&&(r.state=r.stack.pop()),u.data.mode&&a(t,r,u.data.mode,u.token),u.data.indent&&r.indent.push(n.indentation()+t.indentUnit),u.data.dedent&&r.indent.pop();var d=u.token;if(d&&d.apply&&(d=d(f)),f.length>2&&u.token&&"string"!=typeof u.token){r.pending=[];for(var h=2;h<f.length;h++)f[h]&&r.pending.push({text:f[h],token:u.token[h-1]});return n.backUp(f[0].length-(f[1]?f[1].length:0)),d[0]}return d&&d.join?d[0]:d}}return n.next(),null}}function o(e,t){if(e===t)return!0;if(!e||"object"!=typeof e||!t||"object"!=typeof t)return!1;var n=0;for(var r in e)if(e.hasOwnProperty(r)){if(!t.hasOwnProperty(r)||!o(e[r],t[r]))return!1;n++}for(var r in t)t.hasOwnProperty(r)&&n--;return 0==n}function a(t,r,i,a){var l;if(i.persistent)for(var s=r.persistentStates;s&&!l;s=s.next)(i.spec?o(i.spec,s.spec):i.mode==s.mode)&&(l=s);var c=l?l.mode:i.mode||e.getMode(t,i.spec),u=l?l.state:e.startState(c);i.persistent&&!l&&(r.persistentStates={mode:c,spec:i.spec,state:u,next:r.persistentStates}),r.localState=u,r.local={mode:c,end:i.end&&n(i.end),endScan:i.end&&!1!==i.forceEnd&&n(i.end,!1),endToken:a&&a.join?a[a.length-1]:a}}function l(t,n){return function(r,i,o){if(r.local&&r.local.mode.indent)return r.local.mode.indent(r.localState,i,o);if(null==r.indent||r.local||n.dontIndentStates&&function(e,t){for(var n=0;n<t.length;n++)if(t[n]===e)return!0}(r.state,n.dontIndentStates)>-1)return e.Pass;var a=r.indent.length-1,l=t[r.state];e:for(;;){for(var s=0;s<l.length;s++){var c=l[s];if(c.data.dedent&&!1!==c.data.dedentIfLineStart){var u=c.regex.exec(i);if(u&&u[0]){a--,(c.next||c.push)&&(l=t[c.next||c.push]),i=i.slice(u[0].length);continue e}}}break}return a<0?0:r.indent[a]}}e.defineSimpleMode=function(t,n){e.defineMode(t,(function(t){return e.simpleMode(t,n)}))},e.simpleMode=function(n,o){t(o,"start");var a={},s=o.meta||{},c=!1;for(var u in o)if(u!=s&&o.hasOwnProperty(u))for(var f=a[u]=[],d=o[u],h=0;h<d.length;h++){var p=d[h];f.push(new r(p,o)),(p.indent||p.dedent)&&(c=!0)}var m={startState:function(){return{state:"start",pending:null,local:null,localState:null,indent:c?[]:null}},copyState:function(t){var n={state:t.state,pending:t.pending,local:t.local,localState:null,indent:t.indent&&t.indent.slice(0)};t.localState&&(n.localState=e.copyState(t.local.mode,t.localState)),t.stack&&(n.stack=t.stack.slice(0));for(var r=t.persistentStates;r;r=r.next)n.persistentStates={mode:r.mode,spec:r.spec,state:r.state==t.localState?n.localState:e.copyState(r.mode,r.state),next:n.persistentStates};return n},token:i(a,n),innerMode:function(e){return e.local&&{mode:e.local.mode,state:e.localState}},indent:l(a,s)};if(s)for(var g in s)s.hasOwnProperty(g)&&(m[g]=s[g]);return m}}(n(0))},function(e,t,n){var r,i,o;i=[n(0)],void 0===(o="function"==typeof(r=function(e){"use strict";var t=/[\w\$_\.\\\/@]/;function n(e){var t=Object.create(null);return e.forEach((function(e){t[e]=!0})),t}e.defineMode("wasm",(function(){var e=n(["function","import","export","table","memory","segment","as","type","of","from","typeof","br","br_if","loop","br_table","if","else","call","call_import","call_indirect","nop","unreachable","var","align","select","return"]),r=n(["i32:8","i32:8u","i32:8s","i32:16","i32:16u","i32:16s","i64:8","i64:8u","i64:8s","i64:16","i64:16u","i64:16s","i64:32","i64:32u","i64:32s","i32.add","i32.sub","i32.mul","i32.div_s","i32.div_u","i32.rem_s","i32.rem_u","i32.and","i32.or","i32.xor","i32.shl","i32.shr_u","i32.shr_s","i32.rotr","i32.rotl","i32.eq","i32.ne","i32.lt_s","i32.le_s","i32.lt_u","i32.le_u","i32.gt_s","i32.ge_s","i32.gt_u","i32.ge_u","i32.clz","i32.ctz","i32.popcnt","i32.eqz","i64.add","i64.sub","i64.mul","i64.div_s","i64.div_u","i64.rem_s","i64.rem_u","i64.and","i64.or","i64.xor","i64.shl","i64.shr_u","i64.shr_s","i64.rotr","i64.rotl","i64.eq","i64.ne","i64.lt_s","i64.le_s","i64.lt_u","i64.le_u","i64.gt_s","i64.ge_s","i64.gt_u","i64.ge_u","i64.clz","i64.ctz","i64.popcnt","i64.eqz","f32.add","f32.sub","f32.mul","f32.div","f32.min","f32.max","f32.abs","f32.neg","f32.copysign","f32.ceil","f32.floor","f32.trunc","f32.nearest","f32.sqrt","f32.eq","f32.ne","f32.lt","f32.le","f32.gt","f32.ge","f64.add","f64.sub","f64.mul","f64.div","f64.min","f64.max","f64.abs","f64.neg","f64.copysign","f64.ceil","f64.floor","f64.trunc","f64.nearest","f64.sqrt","f64.eq","f64.ne","f64.lt","f64.le","f64.gt","f64.ge","i32.trunc_s/f32","i32.trunc_s/f64","i32.trunc_u/f32","i32.trunc_u/f64","i32.wrap/i64","i64.trunc_s/f32","i64.trunc_s/f64","i64.trunc_u/f32","i64.trunc_u/f64","i64.extend_s/i32","i64.extend_u/i32","f32.convert_s/i32","f32.convert_u/i32","f32.convert_s/i64","f32.convert_u/i64","f32.demote/f64","f32.reinterpret/i32","f64.convert_s/i32","f64.convert_u/i32","f64.convert_s/i64","f64.convert_u/i64","f64.promote/f32","f64.reinterpret/i64","i32.reinterpret/f32","i64.reinterpret/f64"]),i=n(["i32","i64","f32","f64"]),o=/[\-!]/,a=n(["+","-","*","/","/s","/u","%","%s","%u","<<",">>u",">>s",">=","<=","==","!=","<s","<u","<=s","<=u",">=s",">=u",">s",">u","<",">","=","&","|","^","!"]);function l(n,l){var u,f=n.next();if("$"===f)return n.eatWhile(t),"variable";if("@"===f)return n.eatWhile(t),"meta";if('"'===f)return l.tokenize=(u=f,function(e,t){for(var n,r=!1;null!=(n=e.next());){if(n==u&&!r)return t.tokenize=null,"string";r=!r&&"\\"===n}return"string"}),l.tokenize(n,l);if("/"==f){if(n.eat("*"))return l.tokenize=s,s(n,l);if(n.eat("/"))return n.skipToEnd(),"comment"}if(/\d/.test(f)||("-"===f||"+"===f)&&/\d/.test(n.peek()))return n.eatWhile(/[\w\._\-+]/),"number";if(/[\[\]\(\)\{\},:]/.test(f))return null;if(o.test(f))return"operator";n.eatWhile(t);var d=n.current();if(d in a)return"operator";if(d in e)return"keyword";if(d in i){if(!n.eat(":"))return"builtin";n.eatWhile(t),d=n.current()}return d in r?"builtin":"Temporary"===d?(l.tokenize=c,l.tokenize(n,l)):null}function s(e,t){var n;for(t.commentDepth=1;null!=(n=e.next());){if("*"===n&&e.eat("/")&&0==--t.commentDepth)return t.tokenize=null,"comment";"/"===n&&e.eat("*")&&t.commentDepth++}return"comment"}function c(e,t){for(var n,r=t.commentState;null!=(n=e.next());)if(0===r&&"t"===n)r=1;else if(1===r&&":"===n)return t.tokenize=null,t.commentState=0,r=2,"comment";return t.commentState=r,"comment"}return{startState:function(){return{tokenize:null,commentState:0,commentDepth:0}},token:function(e,t){return e.eatSpace()?null:(t.tokenize||l)(e,t)}}})),e.registerHelper("wordChars","wasm",t),e.defineMIME("text/wasm","wasm")})?r.apply(t,i):r)||(e.exports=o)},function(e,t,n){!function(e){"use strict";var t="CodeMirror-activeline-background";function n(e){for(var n=0;n<e.state.activeLines.length;n++)e.removeLineClass(e.state.activeLines[n],"wrap","CodeMirror-activeline"),e.removeLineClass(e.state.activeLines[n],"background",t),e.removeLineClass(e.state.activeLines[n],"gutter","CodeMirror-activeline-gutter")}function r(e,r){for(var i=[],o=0;o<r.length;o++){var a=r[o],l=e.getOption("styleActiveLine");if("object"==typeof l&&l.nonEmpty?a.anchor.line==a.head.line:a.empty()){var s=e.getLineHandleVisualStart(a.head.line);i[i.length-1]!=s&&i.push(s)}}(function(e,t){if(e.length!=t.length)return!1;for(var n=0;n<e.length;n++)if(e[n]!=t[n])return!1;return!0})(e.state.activeLines,i)||e.operation((function(){n(e);for(var r=0;r<i.length;r++)e.addLineClass(i[r],"wrap","CodeMirror-activeline"),e.addLineClass(i[r],"background",t),e.addLineClass(i[r],"gutter","CodeMirror-activeline-gutter");e.state.activeLines=i}))}function i(e,t){r(e,t.ranges)}e.defineOption("styleActiveLine",!1,(function(t,o,a){var l=a!=e.Init&&a;o!=l&&(l&&(t.off("beforeSelectionChange",i),n(t),delete t.state.activeLines),o&&(t.state.activeLines=[],r(t,t.listSelections()),t.on("beforeSelectionChange",i)))}))}(n(0))},function(e,t,n){!function(e){e.defineOption("showTrailingSpace",!1,(function(t,n,r){r==e.Init&&(r=!1),r&&!n?t.removeOverlay("trailingspace"):!r&&n&&t.addOverlay({token:function(e){for(var t=e.string.length,n=t;n&&/\s/.test(e.string.charAt(n-1));--n);return n>e.pos?(e.pos=n,null):(e.pos=t,"trailingspace")},name:"trailingspace"})}))}(n(0))},function(e,t,n){!function(e){"use strict";e.registerHelper("fold","brace",(function(t,n){var r,i=n.line,o=t.getLine(i);function a(a){for(var l=n.ch,s=0;;){var c=l<=0?-1:o.lastIndexOf(a,l-1);if(-1!=c){if(1==s&&c<n.ch)break;if(r=t.getTokenTypeAt(e.Pos(i,c+1)),!/^(comment|string)/.test(r))return c+1;l=c-1}else{if(1==s)break;s=1,l=o.length}}}var l="{",s="}",c=a("{");if(null==c&&(l="[",s="]",c=a("[")),null!=c){var u,f,d=1,h=t.lastLine();e:for(var p=i;p<=h;++p)for(var m=t.getLine(p),g=p==i?c:0;;){var v=m.indexOf(l,g),y=m.indexOf(s,g);if(v<0&&(v=m.length),y<0&&(y=m.length),(g=Math.min(v,y))==m.length)break;if(t.getTokenTypeAt(e.Pos(p,g+1))==r)if(g==v)++d;else if(!--d){u=p,f=g;break e}++g}if(null!=u&&i!=u)return{from:e.Pos(i,c),to:e.Pos(u,f)}}})),e.registerHelper("fold","import",(function(t,n){function r(n){if(n<t.firstLine()||n>t.lastLine())return null;var r=t.getTokenAt(e.Pos(n,1));if(/\S/.test(r.string)||(r=t.getTokenAt(e.Pos(n,r.end+1))),"keyword"!=r.type||"import"!=r.string)return null;for(var i=n,o=Math.min(t.lastLine(),n+10);i<=o;++i){var a=t.getLine(i).indexOf(";");if(-1!=a)return{startCh:r.end,end:e.Pos(i,a)}}}var i,o=n.line,a=r(o);if(!a||r(o-1)||(i=r(o-2))&&i.end.line==o-1)return null;for(var l=a.end;;){var s=r(l.line+1);if(null==s)break;l=s.end}return{from:t.clipPos(e.Pos(o,a.startCh+1)),to:l}})),e.registerHelper("fold","include",(function(t,n){function r(n){if(n<t.firstLine()||n>t.lastLine())return null;var r=t.getTokenAt(e.Pos(n,1));return/\S/.test(r.string)||(r=t.getTokenAt(e.Pos(n,r.end+1))),"meta"==r.type&&"#include"==r.string.slice(0,8)?r.start+8:void 0}var i=n.line,o=r(i);if(null==o||null!=r(i-1))return null;for(var a=i;null!=r(a+1);)++a;return{from:e.Pos(i,o+1),to:t.clipPos(e.Pos(a))}}))}(n(0))},function(e,t,n){!function(e){"use strict";e.registerGlobalHelper("fold","comment",(function(e){return e.blockCommentStart&&e.blockCommentEnd}),(function(t,n){var r=t.getModeAt(n),i=r.blockCommentStart,o=r.blockCommentEnd;if(i&&o){for(var a,l=n.line,s=t.getLine(l),c=n.ch,u=0;;){var f=c<=0?-1:s.lastIndexOf(i,c-1);if(-1!=f){if(1==u&&f<n.ch)return;if(/comment/.test(t.getTokenTypeAt(e.Pos(l,f+1)))&&(0==f||s.slice(f-o.length,f)==o||!/comment/.test(t.getTokenTypeAt(e.Pos(l,f))))){a=f+i.length;break}c=f-1}else{if(1==u)return;u=1,c=s.length}}var d,h,p=1,m=t.lastLine();e:for(var g=l;g<=m;++g)for(var v=t.getLine(g),y=g==l?a:0;;){var b=v.indexOf(i,y),x=v.indexOf(o,y);if(b<0&&(b=v.length),x<0&&(x=v.length),(y=Math.min(b,x))==v.length)break;if(y==b)++p;else if(!--p){d=g,h=y;break e}++y}if(null!=d&&(l!=d||h!=a))return{from:e.Pos(l,a),to:e.Pos(d,h)}}}))}(n(0))},function(e,t,n){!function(e){"use strict";var t=e.Pos;function n(e,t){return e.line-t.line||e.ch-t.ch}var r="A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",i=new RegExp("<(/?)(["+r+"]["+r+"-:.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*)","g");function o(e,t,n,r){this.line=t,this.ch=n,this.cm=e,this.text=e.getLine(t),this.min=r?Math.max(r.from,e.firstLine()):e.firstLine(),this.max=r?Math.min(r.to-1,e.lastLine()):e.lastLine()}function a(e,n){var r=e.cm.getTokenTypeAt(t(e.line,n));return r&&/\btag\b/.test(r)}function l(e){if(!(e.line>=e.max))return e.ch=0,e.text=e.cm.getLine(++e.line),!0}function s(e){if(!(e.line<=e.min))return e.text=e.cm.getLine(--e.line),e.ch=e.text.length,!0}function c(e){for(;;){var t=e.text.indexOf(">",e.ch);if(-1==t){if(l(e))continue;return}if(a(e,t+1)){var n=e.text.lastIndexOf("/",t),r=n>-1&&!/\S/.test(e.text.slice(n+1,t));return e.ch=t+1,r?"selfClose":"regular"}e.ch=t+1}}function u(e){for(;;){var t=e.ch?e.text.lastIndexOf("<",e.ch-1):-1;if(-1==t){if(s(e))continue;return}if(a(e,t+1)){i.lastIndex=t,e.ch=t;var n=i.exec(e.text);if(n&&n.index==t)return n}else e.ch=t}}function f(e){for(;;){i.lastIndex=e.ch;var t=i.exec(e.text);if(!t){if(l(e))continue;return}if(a(e,t.index+1))return e.ch=t.index+t[0].length,t;e.ch=t.index+1}}function d(e){for(;;){var t=e.ch?e.text.lastIndexOf(">",e.ch-1):-1;if(-1==t){if(s(e))continue;return}if(a(e,t+1)){var n=e.text.lastIndexOf("/",t),r=n>-1&&!/\S/.test(e.text.slice(n+1,t));return e.ch=t+1,r?"selfClose":"regular"}e.ch=t}}function h(e,n){for(var r=[];;){var i,o=f(e),a=e.line,l=e.ch-(o?o[0].length:0);if(!o||!(i=c(e)))return;if("selfClose"!=i)if(o[1]){for(var s=r.length-1;s>=0;--s)if(r[s]==o[2]){r.length=s;break}if(s<0&&(!n||n==o[2]))return{tag:o[2],from:t(a,l),to:t(e.line,e.ch)}}else r.push(o[2])}}function p(e,n){for(var r=[];;){var i=d(e);if(!i)return;if("selfClose"!=i){var o=e.line,a=e.ch,l=u(e);if(!l)return;if(l[1])r.push(l[2]);else{for(var s=r.length-1;s>=0;--s)if(r[s]==l[2]){r.length=s;break}if(s<0&&(!n||n==l[2]))return{tag:l[2],from:t(e.line,e.ch),to:t(o,a)}}}else u(e)}}e.registerHelper("fold","xml",(function(e,r){for(var i=new o(e,r.line,0);;){var a=f(i);if(!a||i.line!=r.line)return;var l=c(i);if(!l)return;if(!a[1]&&"selfClose"!=l){var s=t(i.line,i.ch),u=h(i,a[2]);return u&&n(u.from,s)>0?{from:s,to:u.from}:null}}})),e.findMatchingTag=function(e,r,i){var a=new o(e,r.line,r.ch,i);if(-1!=a.text.indexOf(">")||-1!=a.text.indexOf("<")){var l=c(a),s=l&&t(a.line,a.ch),f=l&&u(a);if(l&&f&&!(n(a,r)>0)){var d={from:t(a.line,a.ch),to:s,tag:f[2]};return"selfClose"==l?{open:d,close:null,at:"open"}:f[1]?{open:p(a,f[2]),close:d,at:"close"}:{open:d,close:h(a=new o(e,s.line,s.ch,i),f[2]),at:"open"}}}},e.findEnclosingTag=function(e,t,n,r){for(var i=new o(e,t.line,t.ch,n);;){var a=p(i,r);if(!a)break;var l=h(new o(e,t.line,t.ch,n),a.tag);if(l)return{open:a,close:l}}},e.scanForClosingTag=function(e,t,n,r){return h(new o(e,t.line,t.ch,r?{from:0,to:r}:null),n)}}(n(0))},function(e,t,n){!function(e){"use strict";e.defineOption("foldGutter",!1,(function(t,r,i){var o;i&&i!=e.Init&&(t.clearGutter(t.state.foldGutter.options.gutter),t.state.foldGutter=null,t.off("gutterClick",l),t.off("changes",s),t.off("viewportChange",c),t.off("fold",u),t.off("unfold",u),t.off("swapDoc",s)),r&&(t.state.foldGutter=new n((!0===(o=r)&&(o={}),null==o.gutter&&(o.gutter="CodeMirror-foldgutter"),null==o.indicatorOpen&&(o.indicatorOpen="CodeMirror-foldgutter-open"),null==o.indicatorFolded&&(o.indicatorFolded="CodeMirror-foldgutter-folded"),o)),a(t),t.on("gutterClick",l),t.on("changes",s),t.on("viewportChange",c),t.on("fold",u),t.on("unfold",u),t.on("swapDoc",s))}));var t=e.Pos;function n(e){this.options=e,this.from=this.to=0}function r(e,n){for(var r=e.findMarks(t(n,0),t(n+1,0)),i=0;i<r.length;++i)if(r[i].__isFold){var o=r[i].find(-1);if(o&&o.line===n)return r[i]}}function i(e){if("string"==typeof e){var t=document.createElement("div");return t.className=e+" CodeMirror-guttermarker-subtle",t}return e.cloneNode(!0)}function o(e,n,o){var a=e.state.foldGutter.options,l=n,s=e.foldOption(a,"minFoldSize"),c=e.foldOption(a,"rangeFinder");e.eachLine(n,o,(function(n){var o=null;if(r(e,l))o=i(a.indicatorFolded);else{var u=t(l,0),f=c&&c(e,u);f&&f.to.line-f.from.line>=s&&(o=i(a.indicatorOpen))}e.setGutterMarker(n,a.gutter,o),++l}))}function a(e){var t=e.getViewport(),n=e.state.foldGutter;n&&(e.operation((function(){o(e,t.from,t.to)})),n.from=t.from,n.to=t.to)}function l(e,n,i){var o=e.state.foldGutter;if(o){var a=o.options;if(i==a.gutter){var l=r(e,n);l?l.clear():e.foldCode(t(n,0),a)}}}function s(e){var t=e.state.foldGutter;if(t){var n=t.options;t.from=t.to=0,clearTimeout(t.changeUpdate),t.changeUpdate=setTimeout((function(){a(e)}),n.foldOnChangeTimeSpan||600)}}function c(e){var t=e.state.foldGutter;if(t){var n=t.options;clearTimeout(t.changeUpdate),t.changeUpdate=setTimeout((function(){var n=e.getViewport();t.from==t.to||n.from-t.to>20||t.from-n.to>20?a(e):e.operation((function(){n.from<t.from&&(o(e,n.from,t.from),t.from=n.from),n.to>t.to&&(o(e,t.to,n.to),t.to=n.to)}))}),n.updateViewportTimeSpan||400)}}function u(e,t){var n=e.state.foldGutter;if(n){var r=t.line;r>=n.from&&r<n.to&&o(e,r,r+1)}}}(n(0),n(6))},function(e,t,n){!function(e){"use strict";e.runMode=function(t,n,r,i){var o=e.getMode(e.defaults,n),a=/MSIE \d/.test(navigator.userAgent)&&(null==document.documentMode||document.documentMode<9);if(r.appendChild){var l=i&&i.tabSize||e.defaults.tabSize,s=r,c=0;s.innerHTML="",r=function(e,t){if("\n"==e)return s.appendChild(document.createTextNode(a?"\r":e)),void(c=0);for(var n="",r=0;;){var i=e.indexOf("\t",r);if(-1==i){n+=e.slice(r),c+=e.length-r;break}c+=i-r,n+=e.slice(r,i);var o=l-c%l;c+=o;for(var u=0;u<o;++u)n+=" ";r=i+1}if(t){var f=s.appendChild(document.createElement("span"));f.className="cm-"+t.replace(/ +/g," cm-"),f.appendChild(document.createTextNode(n))}else s.appendChild(document.createTextNode(n))}}for(var u=e.splitLines(t),f=i&&i.state||e.startState(o),d=0,h=u.length;d<h;++d){d&&r("\n");var p=new e.StringStream(u[d]);for(!p.string&&o.blankLine&&o.blankLine(f);!p.eol();){var m=o.token(p,f);r(p.current(),m,d,p.start,f),p.start=p.pos}}}}(n(0))},function(e,t,n){!function(e){function t(e){e.state.placeholder&&(e.state.placeholder.parentNode.removeChild(e.state.placeholder),e.state.placeholder=null)}function n(e){t(e);var n=e.state.placeholder=document.createElement("pre");n.style.cssText="height: 0; overflow: visible",n.style.direction=e.getOption("direction"),n.className="CodeMirror-placeholder CodeMirror-line-like";var r=e.getOption("placeholder");"string"==typeof r&&(r=document.createTextNode(r)),n.appendChild(r),e.display.lineSpace.insertBefore(n,e.display.lineSpace.firstChild)}function r(e){o(e)&&n(e)}function i(e){var r=e.getWrapperElement(),i=o(e);r.className=r.className.replace(" CodeMirror-empty","")+(i?" CodeMirror-empty":""),i?n(e):t(e)}function o(e){return 1===e.lineCount()&&""===e.getLine(0)}e.defineOption("placeholder","",(function(n,o,a){var l=a&&a!=e.Init;if(o&&!l)n.on("blur",r),n.on("change",i),n.on("swapDoc",i),i(n);else if(!o&&l){n.off("blur",r),n.off("change",i),n.off("swapDoc",i),t(n);var s=n.getWrapperElement();s.className=s.className.replace(" CodeMirror-empty","")}o&&!n.hasFocus()&&r(n)}))}(n(0))}]); \ No newline at end of file
diff --git a/devtools/client/shared/sourceeditor/codemirror/keymap/emacs.js b/devtools/client/shared/sourceeditor/codemirror/keymap/emacs.js
new file mode 100644
index 0000000000..dd1db727e0
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/keymap/emacs.js
@@ -0,0 +1,418 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ var Pos = CodeMirror.Pos;
+ function posEq(a, b) { return a.line == b.line && a.ch == b.ch; }
+
+ // Kill 'ring'
+
+ var killRing = [];
+ function addToRing(str) {
+ killRing.push(str);
+ if (killRing.length > 50) killRing.shift();
+ }
+ function growRingTop(str) {
+ if (!killRing.length) return addToRing(str);
+ killRing[killRing.length - 1] += str;
+ }
+ function getFromRing(n) { return killRing[killRing.length - (n ? Math.min(n, 1) : 1)] || ""; }
+ function popFromRing() { if (killRing.length > 1) killRing.pop(); return getFromRing(); }
+
+ var lastKill = null;
+
+ function kill(cm, from, to, ring, text) {
+ if (text == null) text = cm.getRange(from, to);
+
+ if (ring == "grow" && lastKill && lastKill.cm == cm && posEq(from, lastKill.pos) && cm.isClean(lastKill.gen))
+ growRingTop(text);
+ else if (ring !== false)
+ addToRing(text);
+ cm.replaceRange("", from, to, "+delete");
+
+ if (ring == "grow") lastKill = {cm: cm, pos: from, gen: cm.changeGeneration()};
+ else lastKill = null;
+ }
+
+ // Boundaries of various units
+
+ function byChar(cm, pos, dir) {
+ return cm.findPosH(pos, dir, "char", true);
+ }
+
+ function byWord(cm, pos, dir) {
+ return cm.findPosH(pos, dir, "word", true);
+ }
+
+ function byLine(cm, pos, dir) {
+ return cm.findPosV(pos, dir, "line", cm.doc.sel.goalColumn);
+ }
+
+ function byPage(cm, pos, dir) {
+ return cm.findPosV(pos, dir, "page", cm.doc.sel.goalColumn);
+ }
+
+ function byParagraph(cm, pos, dir) {
+ var no = pos.line, line = cm.getLine(no);
+ var sawText = /\S/.test(dir < 0 ? line.slice(0, pos.ch) : line.slice(pos.ch));
+ var fst = cm.firstLine(), lst = cm.lastLine();
+ for (;;) {
+ no += dir;
+ if (no < fst || no > lst)
+ return cm.clipPos(Pos(no - dir, dir < 0 ? 0 : null));
+ line = cm.getLine(no);
+ var hasText = /\S/.test(line);
+ if (hasText) sawText = true;
+ else if (sawText) return Pos(no, 0);
+ }
+ }
+
+ function bySentence(cm, pos, dir) {
+ var line = pos.line, ch = pos.ch;
+ var text = cm.getLine(pos.line), sawWord = false;
+ for (;;) {
+ var next = text.charAt(ch + (dir < 0 ? -1 : 0));
+ if (!next) { // End/beginning of line reached
+ if (line == (dir < 0 ? cm.firstLine() : cm.lastLine())) return Pos(line, ch);
+ text = cm.getLine(line + dir);
+ if (!/\S/.test(text)) return Pos(line, ch);
+ line += dir;
+ ch = dir < 0 ? text.length : 0;
+ continue;
+ }
+ if (sawWord && /[!?.]/.test(next)) return Pos(line, ch + (dir > 0 ? 1 : 0));
+ if (!sawWord) sawWord = /\w/.test(next);
+ ch += dir;
+ }
+ }
+
+ function byExpr(cm, pos, dir) {
+ var wrap;
+ if (cm.findMatchingBracket && (wrap = cm.findMatchingBracket(pos, {strict: true}))
+ && wrap.match && (wrap.forward ? 1 : -1) == dir)
+ return dir > 0 ? Pos(wrap.to.line, wrap.to.ch + 1) : wrap.to;
+
+ for (var first = true;; first = false) {
+ var token = cm.getTokenAt(pos);
+ var after = Pos(pos.line, dir < 0 ? token.start : token.end);
+ if (first && dir > 0 && token.end == pos.ch || !/\w/.test(token.string)) {
+ var newPos = cm.findPosH(after, dir, "char");
+ if (posEq(after, newPos)) return pos;
+ else pos = newPos;
+ } else {
+ return after;
+ }
+ }
+ }
+
+ // Prefixes (only crudely supported)
+
+ function getPrefix(cm, precise) {
+ var digits = cm.state.emacsPrefix;
+ if (!digits) return precise ? null : 1;
+ clearPrefix(cm);
+ return digits == "-" ? -1 : Number(digits);
+ }
+
+ function repeated(cmd) {
+ var f = typeof cmd == "string" ? function(cm) { cm.execCommand(cmd); } : cmd;
+ return function(cm) {
+ var prefix = getPrefix(cm);
+ f(cm);
+ for (var i = 1; i < prefix; ++i) f(cm);
+ };
+ }
+
+ function findEnd(cm, pos, by, dir) {
+ var prefix = getPrefix(cm);
+ if (prefix < 0) { dir = -dir; prefix = -prefix; }
+ for (var i = 0; i < prefix; ++i) {
+ var newPos = by(cm, pos, dir);
+ if (posEq(newPos, pos)) break;
+ pos = newPos;
+ }
+ return pos;
+ }
+
+ function move(by, dir) {
+ var f = function(cm) {
+ cm.extendSelection(findEnd(cm, cm.getCursor(), by, dir));
+ };
+ f.motion = true;
+ return f;
+ }
+
+ function killTo(cm, by, dir, ring) {
+ var selections = cm.listSelections(), cursor;
+ var i = selections.length;
+ while (i--) {
+ cursor = selections[i].head;
+ kill(cm, cursor, findEnd(cm, cursor, by, dir), ring);
+ }
+ }
+
+ function killRegion(cm, ring) {
+ if (cm.somethingSelected()) {
+ var selections = cm.listSelections(), selection;
+ var i = selections.length;
+ while (i--) {
+ selection = selections[i];
+ kill(cm, selection.anchor, selection.head, ring);
+ }
+ return true;
+ }
+ }
+
+ function addPrefix(cm, digit) {
+ if (cm.state.emacsPrefix) {
+ if (digit != "-") cm.state.emacsPrefix += digit;
+ return;
+ }
+ // Not active yet
+ cm.state.emacsPrefix = digit;
+ cm.on("keyHandled", maybeClearPrefix);
+ cm.on("inputRead", maybeDuplicateInput);
+ }
+
+ var prefixPreservingKeys = {"Alt-G": true, "Ctrl-X": true, "Ctrl-Q": true, "Ctrl-U": true};
+
+ function maybeClearPrefix(cm, arg) {
+ if (!cm.state.emacsPrefixMap && !prefixPreservingKeys.hasOwnProperty(arg))
+ clearPrefix(cm);
+ }
+
+ function clearPrefix(cm) {
+ cm.state.emacsPrefix = null;
+ cm.off("keyHandled", maybeClearPrefix);
+ cm.off("inputRead", maybeDuplicateInput);
+ }
+
+ function maybeDuplicateInput(cm, event) {
+ var dup = getPrefix(cm);
+ if (dup > 1 && event.origin == "+input") {
+ var one = event.text.join("\n"), txt = "";
+ for (var i = 1; i < dup; ++i) txt += one;
+ cm.replaceSelection(txt);
+ }
+ }
+
+ function addPrefixMap(cm) {
+ cm.state.emacsPrefixMap = true;
+ cm.addKeyMap(prefixMap);
+ cm.on("keyHandled", maybeRemovePrefixMap);
+ cm.on("inputRead", maybeRemovePrefixMap);
+ }
+
+ function maybeRemovePrefixMap(cm, arg) {
+ if (typeof arg == "string" && (/^\d$/.test(arg) || arg == "Ctrl-U")) return;
+ cm.removeKeyMap(prefixMap);
+ cm.state.emacsPrefixMap = false;
+ cm.off("keyHandled", maybeRemovePrefixMap);
+ cm.off("inputRead", maybeRemovePrefixMap);
+ }
+
+ // Utilities
+
+ function setMark(cm) {
+ cm.setCursor(cm.getCursor());
+ cm.setExtending(!cm.getExtending());
+ cm.on("change", function() { cm.setExtending(false); });
+ }
+
+ function clearMark(cm) {
+ cm.setExtending(false);
+ cm.setCursor(cm.getCursor());
+ }
+
+ function getInput(cm, msg, f) {
+ if (cm.openDialog)
+ cm.openDialog(msg + ": <input type=\"text\" style=\"width: 10em\"/>", f, {bottom: true});
+ else
+ f(prompt(msg, ""));
+ }
+
+ function operateOnWord(cm, op) {
+ var start = cm.getCursor(), end = cm.findPosH(start, 1, "word");
+ cm.replaceRange(op(cm.getRange(start, end)), start, end);
+ cm.setCursor(end);
+ }
+
+ function toEnclosingExpr(cm) {
+ var pos = cm.getCursor(), line = pos.line, ch = pos.ch;
+ var stack = [];
+ while (line >= cm.firstLine()) {
+ var text = cm.getLine(line);
+ for (var i = ch == null ? text.length : ch; i > 0;) {
+ var ch = text.charAt(--i);
+ if (ch == ")")
+ stack.push("(");
+ else if (ch == "]")
+ stack.push("[");
+ else if (ch == "}")
+ stack.push("{");
+ else if (/[\(\{\[]/.test(ch) && (!stack.length || stack.pop() != ch))
+ return cm.extendSelection(Pos(line, i));
+ }
+ --line; ch = null;
+ }
+ }
+
+ function quit(cm) {
+ cm.execCommand("clearSearch");
+ clearMark(cm);
+ }
+
+ CodeMirror.emacs = {kill: kill, killRegion: killRegion, repeated: repeated};
+
+ // Actual keymap
+
+ var keyMap = CodeMirror.keyMap.emacs = CodeMirror.normalizeKeyMap({
+ "Ctrl-W": function(cm) {kill(cm, cm.getCursor("start"), cm.getCursor("end"), true);},
+ "Ctrl-K": repeated(function(cm) {
+ var start = cm.getCursor(), end = cm.clipPos(Pos(start.line));
+ var text = cm.getRange(start, end);
+ if (!/\S/.test(text)) {
+ text += "\n";
+ end = Pos(start.line + 1, 0);
+ }
+ kill(cm, start, end, "grow", text);
+ }),
+ "Alt-W": function(cm) {
+ addToRing(cm.getSelection());
+ clearMark(cm);
+ },
+ "Ctrl-Y": function(cm) {
+ var start = cm.getCursor();
+ cm.replaceRange(getFromRing(getPrefix(cm)), start, start, "paste");
+ cm.setSelection(start, cm.getCursor());
+ },
+ "Alt-Y": function(cm) {cm.replaceSelection(popFromRing(), "around", "paste");},
+
+ "Ctrl-Space": setMark, "Ctrl-Shift-2": setMark,
+
+ "Ctrl-F": move(byChar, 1), "Ctrl-B": move(byChar, -1),
+ "Right": move(byChar, 1), "Left": move(byChar, -1),
+ "Ctrl-D": function(cm) { killTo(cm, byChar, 1, false); },
+ "Delete": function(cm) { killRegion(cm, false) || killTo(cm, byChar, 1, false); },
+ "Ctrl-H": function(cm) { killTo(cm, byChar, -1, false); },
+ "Backspace": function(cm) { killRegion(cm, false) || killTo(cm, byChar, -1, false); },
+
+ "Alt-F": move(byWord, 1), "Alt-B": move(byWord, -1),
+ "Alt-Right": move(byWord, 1), "Alt-Left": move(byWord, -1),
+ "Alt-D": function(cm) { killTo(cm, byWord, 1, "grow"); },
+ "Alt-Backspace": function(cm) { killTo(cm, byWord, -1, "grow"); },
+
+ "Ctrl-N": move(byLine, 1), "Ctrl-P": move(byLine, -1),
+ "Down": move(byLine, 1), "Up": move(byLine, -1),
+ "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd",
+ "End": "goLineEnd", "Home": "goLineStart",
+
+ "Alt-V": move(byPage, -1), "Ctrl-V": move(byPage, 1),
+ "PageUp": move(byPage, -1), "PageDown": move(byPage, 1),
+
+ "Ctrl-Up": move(byParagraph, -1), "Ctrl-Down": move(byParagraph, 1),
+
+ "Alt-A": move(bySentence, -1), "Alt-E": move(bySentence, 1),
+ "Alt-K": function(cm) { killTo(cm, bySentence, 1, "grow"); },
+
+ "Ctrl-Alt-K": function(cm) { killTo(cm, byExpr, 1, "grow"); },
+ "Ctrl-Alt-Backspace": function(cm) { killTo(cm, byExpr, -1, "grow"); },
+ "Ctrl-Alt-F": move(byExpr, 1), "Ctrl-Alt-B": move(byExpr, -1, "grow"),
+
+ "Shift-Ctrl-Alt-2": function(cm) {
+ var cursor = cm.getCursor();
+ cm.setSelection(findEnd(cm, cursor, byExpr, 1), cursor);
+ },
+ "Ctrl-Alt-T": function(cm) {
+ var leftStart = byExpr(cm, cm.getCursor(), -1), leftEnd = byExpr(cm, leftStart, 1);
+ var rightEnd = byExpr(cm, leftEnd, 1), rightStart = byExpr(cm, rightEnd, -1);
+ cm.replaceRange(cm.getRange(rightStart, rightEnd) + cm.getRange(leftEnd, rightStart) +
+ cm.getRange(leftStart, leftEnd), leftStart, rightEnd);
+ },
+ "Ctrl-Alt-U": repeated(toEnclosingExpr),
+
+ "Alt-Space": function(cm) {
+ var pos = cm.getCursor(), from = pos.ch, to = pos.ch, text = cm.getLine(pos.line);
+ while (from && /\s/.test(text.charAt(from - 1))) --from;
+ while (to < text.length && /\s/.test(text.charAt(to))) ++to;
+ cm.replaceRange(" ", Pos(pos.line, from), Pos(pos.line, to));
+ },
+ "Ctrl-O": repeated(function(cm) { cm.replaceSelection("\n", "start"); }),
+ "Ctrl-T": repeated(function(cm) {
+ cm.execCommand("transposeChars");
+ }),
+
+ "Alt-C": repeated(function(cm) {
+ operateOnWord(cm, function(w) {
+ var letter = w.search(/\w/);
+ if (letter == -1) return w;
+ return w.slice(0, letter) + w.charAt(letter).toUpperCase() + w.slice(letter + 1).toLowerCase();
+ });
+ }),
+ "Alt-U": repeated(function(cm) {
+ operateOnWord(cm, function(w) { return w.toUpperCase(); });
+ }),
+ "Alt-L": repeated(function(cm) {
+ operateOnWord(cm, function(w) { return w.toLowerCase(); });
+ }),
+
+ "Alt-;": "toggleComment",
+
+ "Ctrl-/": repeated("undo"), "Shift-Ctrl--": repeated("undo"),
+ "Ctrl-Z": repeated("undo"), "Cmd-Z": repeated("undo"),
+ "Shift-Ctrl-Z": "redo",
+ "Shift-Alt-,": "goDocStart", "Shift-Alt-.": "goDocEnd",
+ "Ctrl-S": "findPersistentNext", "Ctrl-R": "findPersistentPrev", "Ctrl-G": quit, "Shift-Alt-5": "replace",
+ "Alt-/": "autocomplete",
+ "Enter": "newlineAndIndent",
+ "Ctrl-J": repeated(function(cm) { cm.replaceSelection("\n", "end"); }),
+ "Tab": "indentAuto",
+
+ "Alt-G G": function(cm) {
+ var prefix = getPrefix(cm, true);
+ if (prefix != null && prefix > 0) return cm.setCursor(prefix - 1);
+
+ getInput(cm, "Goto line", function(str) {
+ var num;
+ if (str && !isNaN(num = Number(str)) && num == (num|0) && num > 0)
+ cm.setCursor(num - 1);
+ });
+ },
+
+ "Ctrl-X Tab": function(cm) {
+ cm.indentSelection(getPrefix(cm, true) || cm.getOption("indentUnit"));
+ },
+ "Ctrl-X Ctrl-X": function(cm) {
+ cm.setSelection(cm.getCursor("head"), cm.getCursor("anchor"));
+ },
+ "Ctrl-X Ctrl-S": "save",
+ "Ctrl-X Ctrl-W": "save",
+ "Ctrl-X S": "saveAll",
+ "Ctrl-X F": "open",
+ "Ctrl-X U": repeated("undo"),
+ "Ctrl-X K": "close",
+ "Ctrl-X Delete": function(cm) { kill(cm, cm.getCursor(), bySentence(cm, cm.getCursor(), 1), "grow"); },
+ "Ctrl-X H": "selectAll",
+
+ "Ctrl-Q Tab": repeated("insertTab"),
+ "Ctrl-U": addPrefixMap
+ });
+
+ var prefixMap = {"Ctrl-G": clearPrefix};
+ function regPrefix(d) {
+ prefixMap[d] = function(cm) { addPrefix(cm, d); };
+ keyMap["Ctrl-" + d] = function(cm) { addPrefix(cm, d); };
+ prefixPreservingKeys["Ctrl-" + d] = true;
+ }
+ for (var i = 0; i < 10; ++i) regPrefix(String(i));
+ regPrefix("-");
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/keymap/sublime.js b/devtools/client/shared/sourceeditor/codemirror/keymap/sublime.js
new file mode 100644
index 0000000000..6bb92edbd9
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/keymap/sublime.js
@@ -0,0 +1,691 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+// A rough approximation of Sublime Text's keybindings
+// Depends on addon/search/searchcursor.js and optionally addon/dialog/dialogs.js
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"), require("resource://devtools/client/shared/sourceeditor/codemirror/addon/search/searchcursor.js"), require("resource://devtools/client/shared/sourceeditor/codemirror/addon/edit/matchbrackets.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../lib/codemirror", "../addon/search/searchcursor", "../addon/edit/matchbrackets"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ var cmds = CodeMirror.commands;
+ var Pos = CodeMirror.Pos;
+
+ // This is not exactly Sublime's algorithm. I couldn't make heads or tails of that.
+ function findPosSubword(doc, start, dir) {
+ if (dir < 0 && start.ch == 0) return doc.clipPos(Pos(start.line - 1));
+ var line = doc.getLine(start.line);
+ if (dir > 0 && start.ch >= line.length) return doc.clipPos(Pos(start.line + 1, 0));
+ var state = "start", type;
+ for (var pos = start.ch, e = dir < 0 ? 0 : line.length, i = 0; pos != e; pos += dir, i++) {
+ var next = line.charAt(dir < 0 ? pos - 1 : pos);
+ var cat = next != "_" && CodeMirror.isWordChar(next) ? "w" : "o";
+ if (cat == "w" && next.toUpperCase() == next) cat = "W";
+ if (state == "start") {
+ if (cat != "o") { state = "in"; type = cat; }
+ } else if (state == "in") {
+ if (type != cat) {
+ if (type == "w" && cat == "W" && dir < 0) pos--;
+ if (type == "W" && cat == "w" && dir > 0) { type = "w"; continue; }
+ break;
+ }
+ }
+ }
+ return Pos(start.line, pos);
+ }
+
+ function moveSubword(cm, dir) {
+ cm.extendSelectionsBy(function(range) {
+ if (cm.display.shift || cm.doc.extend || range.empty())
+ return findPosSubword(cm.doc, range.head, dir);
+ else
+ return dir < 0 ? range.from() : range.to();
+ });
+ }
+
+ cmds.goSubwordLeft = function(cm) { moveSubword(cm, -1); };
+ cmds.goSubwordRight = function(cm) { moveSubword(cm, 1); };
+
+ cmds.scrollLineUp = function(cm) {
+ var info = cm.getScrollInfo();
+ if (!cm.somethingSelected()) {
+ var visibleBottomLine = cm.lineAtHeight(info.top + info.clientHeight, "local");
+ if (cm.getCursor().line >= visibleBottomLine)
+ cm.execCommand("goLineUp");
+ }
+ cm.scrollTo(null, info.top - cm.defaultTextHeight());
+ };
+ cmds.scrollLineDown = function(cm) {
+ var info = cm.getScrollInfo();
+ if (!cm.somethingSelected()) {
+ var visibleTopLine = cm.lineAtHeight(info.top, "local")+1;
+ if (cm.getCursor().line <= visibleTopLine)
+ cm.execCommand("goLineDown");
+ }
+ cm.scrollTo(null, info.top + cm.defaultTextHeight());
+ };
+
+ cmds.splitSelectionByLine = function(cm) {
+ var ranges = cm.listSelections(), lineRanges = [];
+ for (var i = 0; i < ranges.length; i++) {
+ var from = ranges[i].from(), to = ranges[i].to();
+ for (var line = from.line; line <= to.line; ++line)
+ if (!(to.line > from.line && line == to.line && to.ch == 0))
+ lineRanges.push({anchor: line == from.line ? from : Pos(line, 0),
+ head: line == to.line ? to : Pos(line)});
+ }
+ cm.setSelections(lineRanges, 0);
+ };
+
+ cmds.singleSelectionTop = function(cm) {
+ var range = cm.listSelections()[0];
+ cm.setSelection(range.anchor, range.head, {scroll: false});
+ };
+
+ cmds.selectLine = function(cm) {
+ var ranges = cm.listSelections(), extended = [];
+ for (var i = 0; i < ranges.length; i++) {
+ var range = ranges[i];
+ extended.push({anchor: Pos(range.from().line, 0),
+ head: Pos(range.to().line + 1, 0)});
+ }
+ cm.setSelections(extended);
+ };
+
+ function insertLine(cm, above) {
+ if (cm.isReadOnly()) return CodeMirror.Pass
+ cm.operation(function() {
+ var len = cm.listSelections().length, newSelection = [], last = -1;
+ for (var i = 0; i < len; i++) {
+ var head = cm.listSelections()[i].head;
+ if (head.line <= last) continue;
+ var at = Pos(head.line + (above ? 0 : 1), 0);
+ cm.replaceRange("\n", at, null, "+insertLine");
+ cm.indentLine(at.line, null, true);
+ newSelection.push({head: at, anchor: at});
+ last = head.line + 1;
+ }
+ cm.setSelections(newSelection);
+ });
+ cm.execCommand("indentAuto");
+ }
+
+ cmds.insertLineAfter = function(cm) { return insertLine(cm, false); };
+
+ cmds.insertLineBefore = function(cm) { return insertLine(cm, true); };
+
+ function wordAt(cm, pos) {
+ var start = pos.ch, end = start, line = cm.getLine(pos.line);
+ while (start && CodeMirror.isWordChar(line.charAt(start - 1))) --start;
+ while (end < line.length && CodeMirror.isWordChar(line.charAt(end))) ++end;
+ return {from: Pos(pos.line, start), to: Pos(pos.line, end), word: line.slice(start, end)};
+ }
+
+ cmds.selectNextOccurrence = function(cm) {
+ var from = cm.getCursor("from"), to = cm.getCursor("to");
+ var fullWord = cm.state.sublimeFindFullWord == cm.doc.sel;
+ if (CodeMirror.cmpPos(from, to) == 0) {
+ var word = wordAt(cm, from);
+ if (!word.word) return;
+ cm.setSelection(word.from, word.to);
+ fullWord = true;
+ } else {
+ var text = cm.getRange(from, to);
+ var query = fullWord ? new RegExp("\\b" + text + "\\b") : text;
+ var cur = cm.getSearchCursor(query, to);
+ var found = cur.findNext();
+ if (!found) {
+ cur = cm.getSearchCursor(query, Pos(cm.firstLine(), 0));
+ found = cur.findNext();
+ }
+ if (!found || isSelectedRange(cm.listSelections(), cur.from(), cur.to()))
+ return CodeMirror.Pass
+ cm.addSelection(cur.from(), cur.to());
+ }
+ if (fullWord)
+ cm.state.sublimeFindFullWord = cm.doc.sel;
+ };
+
+ function addCursorToSelection(cm, dir) {
+ var ranges = cm.listSelections(), newRanges = [];
+ for (var i = 0; i < ranges.length; i++) {
+ var range = ranges[i];
+ var newAnchor = cm.findPosV(
+ range.anchor, dir, "line", range.anchor.goalColumn);
+ var newHead = cm.findPosV(
+ range.head, dir, "line", range.head.goalColumn);
+ newAnchor.goalColumn = range.anchor.goalColumn != null ?
+ range.anchor.goalColumn : cm.cursorCoords(range.anchor, "div").left;
+ newHead.goalColumn = range.head.goalColumn != null ?
+ range.head.goalColumn : cm.cursorCoords(range.head, "div").left;
+ var newRange = {anchor: newAnchor, head: newHead};
+ newRanges.push(range);
+ newRanges.push(newRange);
+ }
+ cm.setSelections(newRanges);
+ }
+ cmds.addCursorToPrevLine = function(cm) { addCursorToSelection(cm, -1); };
+ cmds.addCursorToNextLine = function(cm) { addCursorToSelection(cm, 1); };
+
+ function isSelectedRange(ranges, from, to) {
+ for (var i = 0; i < ranges.length; i++)
+ if (ranges[i].from() == from && ranges[i].to() == to) return true
+ return false
+ }
+
+ var mirror = "(){}[]";
+ function selectBetweenBrackets(cm) {
+ var ranges = cm.listSelections(), newRanges = []
+ for (var i = 0; i < ranges.length; i++) {
+ var range = ranges[i], pos = range.head, opening = cm.scanForBracket(pos, -1);
+ if (!opening) return false;
+ for (;;) {
+ var closing = cm.scanForBracket(pos, 1);
+ if (!closing) return false;
+ if (closing.ch == mirror.charAt(mirror.indexOf(opening.ch) + 1)) {
+ var startPos = Pos(opening.pos.line, opening.pos.ch + 1);
+ if (CodeMirror.cmpPos(startPos, range.from()) == 0 &&
+ CodeMirror.cmpPos(closing.pos, range.to()) == 0) {
+ opening = cm.scanForBracket(opening.pos, -1);
+ if (!opening) return false;
+ } else {
+ newRanges.push({anchor: startPos, head: closing.pos});
+ break;
+ }
+ }
+ pos = Pos(closing.pos.line, closing.pos.ch + 1);
+ }
+ }
+ cm.setSelections(newRanges);
+ return true;
+ }
+
+ cmds.selectScope = function(cm) {
+ selectBetweenBrackets(cm) || cm.execCommand("selectAll");
+ };
+ cmds.selectBetweenBrackets = function(cm) {
+ if (!selectBetweenBrackets(cm)) return CodeMirror.Pass;
+ };
+
+ cmds.goToBracket = function(cm) {
+ cm.extendSelectionsBy(function(range) {
+ var next = cm.scanForBracket(range.head, 1);
+ if (next && CodeMirror.cmpPos(next.pos, range.head) != 0) return next.pos;
+ var prev = cm.scanForBracket(range.head, -1);
+ return prev && Pos(prev.pos.line, prev.pos.ch + 1) || range.head;
+ });
+ };
+
+ cmds.swapLineUp = function(cm) {
+ if (cm.isReadOnly()) return CodeMirror.Pass
+ var ranges = cm.listSelections(), linesToMove = [], at = cm.firstLine() - 1, newSels = [];
+ for (var i = 0; i < ranges.length; i++) {
+ var range = ranges[i], from = range.from().line - 1, to = range.to().line;
+ newSels.push({anchor: Pos(range.anchor.line - 1, range.anchor.ch),
+ head: Pos(range.head.line - 1, range.head.ch)});
+ if (range.to().ch == 0 && !range.empty()) --to;
+ if (from > at) linesToMove.push(from, to);
+ else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to;
+ at = to;
+ }
+ cm.operation(function() {
+ for (var i = 0; i < linesToMove.length; i += 2) {
+ var from = linesToMove[i], to = linesToMove[i + 1];
+ var line = cm.getLine(from);
+ cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine");
+ if (to > cm.lastLine())
+ cm.replaceRange("\n" + line, Pos(cm.lastLine()), null, "+swapLine");
+ else
+ cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine");
+ }
+ cm.setSelections(newSels);
+ cm.scrollIntoView();
+ });
+ };
+
+ cmds.swapLineDown = function(cm) {
+ if (cm.isReadOnly()) return CodeMirror.Pass
+ var ranges = cm.listSelections(), linesToMove = [], at = cm.lastLine() + 1;
+ for (var i = ranges.length - 1; i >= 0; i--) {
+ var range = ranges[i], from = range.to().line + 1, to = range.from().line;
+ if (range.to().ch == 0 && !range.empty()) from--;
+ if (from < at) linesToMove.push(from, to);
+ else if (linesToMove.length) linesToMove[linesToMove.length - 1] = to;
+ at = to;
+ }
+ cm.operation(function() {
+ for (var i = linesToMove.length - 2; i >= 0; i -= 2) {
+ var from = linesToMove[i], to = linesToMove[i + 1];
+ var line = cm.getLine(from);
+ if (from == cm.lastLine())
+ cm.replaceRange("", Pos(from - 1), Pos(from), "+swapLine");
+ else
+ cm.replaceRange("", Pos(from, 0), Pos(from + 1, 0), "+swapLine");
+ cm.replaceRange(line + "\n", Pos(to, 0), null, "+swapLine");
+ }
+ cm.scrollIntoView();
+ });
+ };
+
+ cmds.toggleCommentIndented = function(cm) {
+ cm.toggleComment({ indent: true });
+ }
+
+ cmds.joinLines = function(cm) {
+ var ranges = cm.listSelections(), joined = [];
+ for (var i = 0; i < ranges.length; i++) {
+ var range = ranges[i], from = range.from();
+ var start = from.line, end = range.to().line;
+ while (i < ranges.length - 1 && ranges[i + 1].from().line == end)
+ end = ranges[++i].to().line;
+ joined.push({start: start, end: end, anchor: !range.empty() && from});
+ }
+ cm.operation(function() {
+ var offset = 0, ranges = [];
+ for (var i = 0; i < joined.length; i++) {
+ var obj = joined[i];
+ var anchor = obj.anchor && Pos(obj.anchor.line - offset, obj.anchor.ch), head;
+ for (var line = obj.start; line <= obj.end; line++) {
+ var actual = line - offset;
+ if (line == obj.end) head = Pos(actual, cm.getLine(actual).length + 1);
+ if (actual < cm.lastLine()) {
+ cm.replaceRange(" ", Pos(actual), Pos(actual + 1, /^\s*/.exec(cm.getLine(actual + 1))[0].length));
+ ++offset;
+ }
+ }
+ ranges.push({anchor: anchor || head, head: head});
+ }
+ cm.setSelections(ranges, 0);
+ });
+ };
+
+ cmds.duplicateLine = function(cm) {
+ cm.operation(function() {
+ var rangeCount = cm.listSelections().length;
+ for (var i = 0; i < rangeCount; i++) {
+ var range = cm.listSelections()[i];
+ if (range.empty())
+ cm.replaceRange(cm.getLine(range.head.line) + "\n", Pos(range.head.line, 0));
+ else
+ cm.replaceRange(cm.getRange(range.from(), range.to()), range.from());
+ }
+ cm.scrollIntoView();
+ });
+ };
+
+
+ function sortLines(cm, caseSensitive) {
+ if (cm.isReadOnly()) return CodeMirror.Pass
+ var ranges = cm.listSelections(), toSort = [], selected;
+ for (var i = 0; i < ranges.length; i++) {
+ var range = ranges[i];
+ if (range.empty()) continue;
+ var from = range.from().line, to = range.to().line;
+ while (i < ranges.length - 1 && ranges[i + 1].from().line == to)
+ to = ranges[++i].to().line;
+ if (!ranges[i].to().ch) to--;
+ toSort.push(from, to);
+ }
+ if (toSort.length) selected = true;
+ else toSort.push(cm.firstLine(), cm.lastLine());
+
+ cm.operation(function() {
+ var ranges = [];
+ for (var i = 0; i < toSort.length; i += 2) {
+ var from = toSort[i], to = toSort[i + 1];
+ var start = Pos(from, 0), end = Pos(to);
+ var lines = cm.getRange(start, end, false);
+ if (caseSensitive)
+ lines.sort();
+ else
+ lines.sort(function(a, b) {
+ var au = a.toUpperCase(), bu = b.toUpperCase();
+ if (au != bu) { a = au; b = bu; }
+ return a < b ? -1 : a == b ? 0 : 1;
+ });
+ cm.replaceRange(lines, start, end);
+ if (selected) ranges.push({anchor: start, head: Pos(to + 1, 0)});
+ }
+ if (selected) cm.setSelections(ranges, 0);
+ });
+ }
+
+ cmds.sortLines = function(cm) { sortLines(cm, true); };
+ cmds.sortLinesInsensitive = function(cm) { sortLines(cm, false); };
+
+ cmds.nextBookmark = function(cm) {
+ var marks = cm.state.sublimeBookmarks;
+ if (marks) while (marks.length) {
+ var current = marks.shift();
+ var found = current.find();
+ if (found) {
+ marks.push(current);
+ return cm.setSelection(found.from, found.to);
+ }
+ }
+ };
+
+ cmds.prevBookmark = function(cm) {
+ var marks = cm.state.sublimeBookmarks;
+ if (marks) while (marks.length) {
+ marks.unshift(marks.pop());
+ var found = marks[marks.length - 1].find();
+ if (!found)
+ marks.pop();
+ else
+ return cm.setSelection(found.from, found.to);
+ }
+ };
+
+ cmds.toggleBookmark = function(cm) {
+ var ranges = cm.listSelections();
+ var marks = cm.state.sublimeBookmarks || (cm.state.sublimeBookmarks = []);
+ for (var i = 0; i < ranges.length; i++) {
+ var from = ranges[i].from(), to = ranges[i].to();
+ var found = ranges[i].empty() ? cm.findMarksAt(from) : cm.findMarks(from, to);
+ for (var j = 0; j < found.length; j++) {
+ if (found[j].sublimeBookmark) {
+ found[j].clear();
+ for (var k = 0; k < marks.length; k++)
+ if (marks[k] == found[j])
+ marks.splice(k--, 1);
+ break;
+ }
+ }
+ if (j == found.length)
+ marks.push(cm.markText(from, to, {sublimeBookmark: true, clearWhenEmpty: false}));
+ }
+ };
+
+ cmds.clearBookmarks = function(cm) {
+ var marks = cm.state.sublimeBookmarks;
+ if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear();
+ marks.length = 0;
+ };
+
+ cmds.selectBookmarks = function(cm) {
+ var marks = cm.state.sublimeBookmarks, ranges = [];
+ if (marks) for (var i = 0; i < marks.length; i++) {
+ var found = marks[i].find();
+ if (!found)
+ marks.splice(i--, 0);
+ else
+ ranges.push({anchor: found.from, head: found.to});
+ }
+ if (ranges.length)
+ cm.setSelections(ranges, 0);
+ };
+
+ function modifyWordOrSelection(cm, mod) {
+ cm.operation(function() {
+ var ranges = cm.listSelections(), indices = [], replacements = [];
+ for (var i = 0; i < ranges.length; i++) {
+ var range = ranges[i];
+ if (range.empty()) { indices.push(i); replacements.push(""); }
+ else replacements.push(mod(cm.getRange(range.from(), range.to())));
+ }
+ cm.replaceSelections(replacements, "around", "case");
+ for (var i = indices.length - 1, at; i >= 0; i--) {
+ var range = ranges[indices[i]];
+ if (at && CodeMirror.cmpPos(range.head, at) > 0) continue;
+ var word = wordAt(cm, range.head);
+ at = word.from;
+ cm.replaceRange(mod(word.word), word.from, word.to);
+ }
+ });
+ }
+
+ cmds.smartBackspace = function(cm) {
+ if (cm.somethingSelected()) return CodeMirror.Pass;
+
+ cm.operation(function() {
+ var cursors = cm.listSelections();
+ var indentUnit = cm.getOption("indentUnit");
+
+ for (var i = cursors.length - 1; i >= 0; i--) {
+ var cursor = cursors[i].head;
+ var toStartOfLine = cm.getRange({line: cursor.line, ch: 0}, cursor);
+ var column = CodeMirror.countColumn(toStartOfLine, null, cm.getOption("tabSize"));
+
+ // Delete by one character by default
+ var deletePos = cm.findPosH(cursor, -1, "char", false);
+
+ if (toStartOfLine && !/\S/.test(toStartOfLine) && column % indentUnit == 0) {
+ var prevIndent = new Pos(cursor.line,
+ CodeMirror.findColumn(toStartOfLine, column - indentUnit, indentUnit));
+
+ // Smart delete only if we found a valid prevIndent location
+ if (prevIndent.ch != cursor.ch) deletePos = prevIndent;
+ }
+
+ cm.replaceRange("", deletePos, cursor, "+delete");
+ }
+ });
+ };
+
+ cmds.delLineRight = function(cm) {
+ cm.operation(function() {
+ var ranges = cm.listSelections();
+ for (var i = ranges.length - 1; i >= 0; i--)
+ cm.replaceRange("", ranges[i].anchor, Pos(ranges[i].to().line), "+delete");
+ cm.scrollIntoView();
+ });
+ };
+
+ cmds.upcaseAtCursor = function(cm) {
+ modifyWordOrSelection(cm, function(str) { return str.toUpperCase(); });
+ };
+ cmds.downcaseAtCursor = function(cm) {
+ modifyWordOrSelection(cm, function(str) { return str.toLowerCase(); });
+ };
+
+ cmds.setSublimeMark = function(cm) {
+ if (cm.state.sublimeMark) cm.state.sublimeMark.clear();
+ cm.state.sublimeMark = cm.setBookmark(cm.getCursor());
+ };
+ cmds.selectToSublimeMark = function(cm) {
+ var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
+ if (found) cm.setSelection(cm.getCursor(), found);
+ };
+ cmds.deleteToSublimeMark = function(cm) {
+ var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
+ if (found) {
+ var from = cm.getCursor(), to = found;
+ if (CodeMirror.cmpPos(from, to) > 0) { var tmp = to; to = from; from = tmp; }
+ cm.state.sublimeKilled = cm.getRange(from, to);
+ cm.replaceRange("", from, to);
+ }
+ };
+ cmds.swapWithSublimeMark = function(cm) {
+ var found = cm.state.sublimeMark && cm.state.sublimeMark.find();
+ if (found) {
+ cm.state.sublimeMark.clear();
+ cm.state.sublimeMark = cm.setBookmark(cm.getCursor());
+ cm.setCursor(found);
+ }
+ };
+ cmds.sublimeYank = function(cm) {
+ if (cm.state.sublimeKilled != null)
+ cm.replaceSelection(cm.state.sublimeKilled, null, "paste");
+ };
+
+ cmds.showInCenter = function(cm) {
+ var pos = cm.cursorCoords(null, "local");
+ cm.scrollTo(null, (pos.top + pos.bottom) / 2 - cm.getScrollInfo().clientHeight / 2);
+ };
+
+ function getTarget(cm) {
+ var from = cm.getCursor("from"), to = cm.getCursor("to");
+ if (CodeMirror.cmpPos(from, to) == 0) {
+ var word = wordAt(cm, from);
+ if (!word.word) return;
+ from = word.from;
+ to = word.to;
+ }
+ return {from: from, to: to, query: cm.getRange(from, to), word: word};
+ }
+
+ function findAndGoTo(cm, forward) {
+ var target = getTarget(cm);
+ if (!target) return;
+ var query = target.query;
+ var cur = cm.getSearchCursor(query, forward ? target.to : target.from);
+
+ if (forward ? cur.findNext() : cur.findPrevious()) {
+ cm.setSelection(cur.from(), cur.to());
+ } else {
+ cur = cm.getSearchCursor(query, forward ? Pos(cm.firstLine(), 0)
+ : cm.clipPos(Pos(cm.lastLine())));
+ if (forward ? cur.findNext() : cur.findPrevious())
+ cm.setSelection(cur.from(), cur.to());
+ else if (target.word)
+ cm.setSelection(target.from, target.to);
+ }
+ };
+ cmds.findUnder = function(cm) { findAndGoTo(cm, true); };
+ cmds.findUnderPrevious = function(cm) { findAndGoTo(cm,false); };
+ cmds.findAllUnder = function(cm) {
+ var target = getTarget(cm);
+ if (!target) return;
+ var cur = cm.getSearchCursor(target.query);
+ var matches = [];
+ var primaryIndex = -1;
+ while (cur.findNext()) {
+ matches.push({anchor: cur.from(), head: cur.to()});
+ if (cur.from().line <= target.from.line && cur.from().ch <= target.from.ch)
+ primaryIndex++;
+ }
+ cm.setSelections(matches, primaryIndex);
+ };
+
+
+ var keyMap = CodeMirror.keyMap;
+ keyMap.macSublime = {
+ "Cmd-Left": "goLineStartSmart",
+ "Shift-Tab": "indentLess",
+ "Shift-Ctrl-K": "deleteLine",
+ "Alt-Q": "wrapLines",
+ "Ctrl-Left": "goSubwordLeft",
+ "Ctrl-Right": "goSubwordRight",
+ "Ctrl-Alt-Up": "scrollLineUp",
+ "Ctrl-Alt-Down": "scrollLineDown",
+ "Cmd-L": "selectLine",
+ "Shift-Cmd-L": "splitSelectionByLine",
+ "Esc": "singleSelectionTop",
+ "Cmd-Enter": "insertLineAfter",
+ "Shift-Cmd-Enter": "insertLineBefore",
+ "Cmd-D": "selectNextOccurrence",
+ "Shift-Cmd-Space": "selectScope",
+ "Shift-Cmd-M": "selectBetweenBrackets",
+ "Cmd-M": "goToBracket",
+ "Cmd-Ctrl-Up": "swapLineUp",
+ "Cmd-Ctrl-Down": "swapLineDown",
+ "Cmd-/": "toggleCommentIndented",
+ "Cmd-J": "joinLines",
+ "Shift-Cmd-D": "duplicateLine",
+ "F5": "sortLines",
+ "Cmd-F5": "sortLinesInsensitive",
+ "F2": "nextBookmark",
+ "Shift-F2": "prevBookmark",
+ "Cmd-F2": "toggleBookmark",
+ "Shift-Cmd-F2": "clearBookmarks",
+ "Alt-F2": "selectBookmarks",
+ "Backspace": "smartBackspace",
+ "Cmd-K Cmd-K": "delLineRight",
+ "Cmd-K Cmd-U": "upcaseAtCursor",
+ "Cmd-K Cmd-L": "downcaseAtCursor",
+ "Cmd-K Cmd-Space": "setSublimeMark",
+ "Cmd-K Cmd-A": "selectToSublimeMark",
+ "Cmd-K Cmd-W": "deleteToSublimeMark",
+ "Cmd-K Cmd-X": "swapWithSublimeMark",
+ "Cmd-K Cmd-Y": "sublimeYank",
+ "Cmd-K Cmd-C": "showInCenter",
+ "Cmd-K Cmd-G": "clearBookmarks",
+ "Cmd-K Cmd-Backspace": "delLineLeft",
+ "Cmd-K Cmd-0": "unfoldAll",
+ "Cmd-K Cmd-J": "unfoldAll",
+ "Ctrl-Shift-Up": "addCursorToPrevLine",
+ "Ctrl-Shift-Down": "addCursorToNextLine",
+ "Cmd-F3": "findUnder",
+ "Shift-Cmd-F3": "findUnderPrevious",
+ "Alt-F3": "findAllUnder",
+ "Shift-Cmd-[": "fold",
+ "Shift-Cmd-]": "unfold",
+ "Cmd-I": "findIncremental",
+ "Shift-Cmd-I": "findIncrementalReverse",
+ "Cmd-H": "replace",
+ "F3": "findNext",
+ "Shift-F3": "findPrev",
+ "fallthrough": "macDefault"
+ };
+ CodeMirror.normalizeKeyMap(keyMap.macSublime);
+
+ keyMap.pcSublime = {
+ "Shift-Tab": "indentLess",
+ "Shift-Ctrl-K": "deleteLine",
+ "Alt-Q": "wrapLines",
+ "Ctrl-T": "transposeChars",
+ "Alt-Left": "goSubwordLeft",
+ "Alt-Right": "goSubwordRight",
+ "Ctrl-Up": "scrollLineUp",
+ "Ctrl-Down": "scrollLineDown",
+ "Ctrl-L": "selectLine",
+ "Shift-Ctrl-L": "splitSelectionByLine",
+ "Esc": "singleSelectionTop",
+ "Ctrl-Enter": "insertLineAfter",
+ "Shift-Ctrl-Enter": "insertLineBefore",
+ "Ctrl-D": "selectNextOccurrence",
+ "Shift-Ctrl-Space": "selectScope",
+ "Shift-Ctrl-M": "selectBetweenBrackets",
+ "Ctrl-M": "goToBracket",
+ "Shift-Ctrl-Up": "swapLineUp",
+ "Shift-Ctrl-Down": "swapLineDown",
+ "Ctrl-/": "toggleCommentIndented",
+ "Ctrl-J": "joinLines",
+ "Shift-Ctrl-D": "duplicateLine",
+ "F9": "sortLines",
+ "Ctrl-F9": "sortLinesInsensitive",
+ "F2": "nextBookmark",
+ "Shift-F2": "prevBookmark",
+ "Ctrl-F2": "toggleBookmark",
+ "Shift-Ctrl-F2": "clearBookmarks",
+ "Alt-F2": "selectBookmarks",
+ "Backspace": "smartBackspace",
+ "Ctrl-K Ctrl-K": "delLineRight",
+ "Ctrl-K Ctrl-U": "upcaseAtCursor",
+ "Ctrl-K Ctrl-L": "downcaseAtCursor",
+ "Ctrl-K Ctrl-Space": "setSublimeMark",
+ "Ctrl-K Ctrl-A": "selectToSublimeMark",
+ "Ctrl-K Ctrl-W": "deleteToSublimeMark",
+ "Ctrl-K Ctrl-X": "swapWithSublimeMark",
+ "Ctrl-K Ctrl-Y": "sublimeYank",
+ "Ctrl-K Ctrl-C": "showInCenter",
+ "Ctrl-K Ctrl-G": "clearBookmarks",
+ "Ctrl-K Ctrl-Backspace": "delLineLeft",
+ "Ctrl-K Ctrl-0": "unfoldAll",
+ "Ctrl-K Ctrl-J": "unfoldAll",
+ "Ctrl-Alt-Up": "addCursorToPrevLine",
+ "Ctrl-Alt-Down": "addCursorToNextLine",
+ "Ctrl-F3": "findUnder",
+ "Shift-Ctrl-F3": "findUnderPrevious",
+ "Alt-F3": "findAllUnder",
+ "Shift-Ctrl-[": "fold",
+ "Shift-Ctrl-]": "unfold",
+ "Ctrl-I": "findIncremental",
+ "Shift-Ctrl-I": "findIncrementalReverse",
+ "Ctrl-H": "replace",
+ "F3": "findNext",
+ "Shift-F3": "findPrev",
+ "fallthrough": "pcDefault"
+ };
+ CodeMirror.normalizeKeyMap(keyMap.pcSublime);
+
+ var mac = keyMap.default == keyMap.macDefault;
+ keyMap.sublime = mac ? keyMap.macSublime : keyMap.pcSublime;
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/keymap/vim.js b/devtools/client/shared/sourceeditor/codemirror/keymap/vim.js
new file mode 100644
index 0000000000..e08ad11808
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/keymap/vim.js
@@ -0,0 +1,5494 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+/**
+ * Supported keybindings:
+ * Too many to list. Refer to defaultKeymap below.
+ *
+ * Supported Ex commands:
+ * Refer to defaultExCommandMap below.
+ *
+ * Registers: unnamed, -, a-z, A-Z, 0-9
+ * (Does not respect the special case for number registers when delete
+ * operator is made with these commands: %, (, ), , /, ?, n, N, {, } )
+ * TODO: Implement the remaining registers.
+ *
+ * Marks: a-z, A-Z, and 0-9
+ * TODO: Implement the remaining special marks. They have more complex
+ * behavior.
+ *
+ * Events:
+ * 'vim-mode-change' - raised on the editor anytime the current mode changes,
+ * Event object: {mode: "visual", subMode: "linewise"}
+ *
+ * Code structure:
+ * 1. Default keymap
+ * 2. Variable declarations and short basic helpers
+ * 3. Instance (External API) implementation
+ * 4. Internal state tracking objects (input state, counter) implementation
+ * and instantiation
+ * 5. Key handler (the main command dispatcher) implementation
+ * 6. Motion, operator, and action implementations
+ * 7. Helper functions for the key handler, motions, operators, and actions
+ * 8. Set up Vim to work as a keymap for CodeMirror.
+ * 9. Ex command implementations.
+ */
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"), require("resource://devtools/client/shared/sourceeditor/codemirror/addon/search/searchcursor.js"), require("resource://devtools/client/shared/sourceeditor/codemirror/addon/dialog/dialog.js"), require("resource://devtools/client/shared/sourceeditor/codemirror/addon/edit/matchbrackets.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../lib/codemirror", "../addon/search/searchcursor", "../addon/dialog/dialog", "../addon/edit/matchbrackets"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ 'use strict';
+
+ var defaultKeymap = [
+ // Key to key mapping. This goes first to make it possible to override
+ // existing mappings.
+ { keys: '<Left>', type: 'keyToKey', toKeys: 'h' },
+ { keys: '<Right>', type: 'keyToKey', toKeys: 'l' },
+ { keys: '<Up>', type: 'keyToKey', toKeys: 'k' },
+ { keys: '<Down>', type: 'keyToKey', toKeys: 'j' },
+ { keys: '<Space>', type: 'keyToKey', toKeys: 'l' },
+ { keys: '<BS>', type: 'keyToKey', toKeys: 'h', context: 'normal'},
+ { keys: '<Del>', type: 'keyToKey', toKeys: 'x', context: 'normal'},
+ { keys: '<C-Space>', type: 'keyToKey', toKeys: 'W' },
+ { keys: '<C-BS>', type: 'keyToKey', toKeys: 'B', context: 'normal' },
+ { keys: '<S-Space>', type: 'keyToKey', toKeys: 'w' },
+ { keys: '<S-BS>', type: 'keyToKey', toKeys: 'b', context: 'normal' },
+ { keys: '<C-n>', type: 'keyToKey', toKeys: 'j' },
+ { keys: '<C-p>', type: 'keyToKey', toKeys: 'k' },
+ { keys: '<C-[>', type: 'keyToKey', toKeys: '<Esc>' },
+ { keys: '<C-c>', type: 'keyToKey', toKeys: '<Esc>' },
+ { keys: '<C-[>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },
+ { keys: '<C-c>', type: 'keyToKey', toKeys: '<Esc>', context: 'insert' },
+ { keys: 's', type: 'keyToKey', toKeys: 'cl', context: 'normal' },
+ { keys: 's', type: 'keyToKey', toKeys: 'c', context: 'visual'},
+ { keys: 'S', type: 'keyToKey', toKeys: 'cc', context: 'normal' },
+ { keys: 'S', type: 'keyToKey', toKeys: 'VdO', context: 'visual' },
+ { keys: '<Home>', type: 'keyToKey', toKeys: '0' },
+ { keys: '<End>', type: 'keyToKey', toKeys: '$' },
+ { keys: '<PageUp>', type: 'keyToKey', toKeys: '<C-b>' },
+ { keys: '<PageDown>', type: 'keyToKey', toKeys: '<C-f>' },
+ { keys: '<CR>', type: 'keyToKey', toKeys: 'j^', context: 'normal' },
+ { keys: '<Ins>', type: 'action', action: 'toggleOverwrite', context: 'insert' },
+ // Motions
+ { keys: 'H', type: 'motion', motion: 'moveToTopLine', motionArgs: { linewise: true, toJumplist: true }},
+ { keys: 'M', type: 'motion', motion: 'moveToMiddleLine', motionArgs: { linewise: true, toJumplist: true }},
+ { keys: 'L', type: 'motion', motion: 'moveToBottomLine', motionArgs: { linewise: true, toJumplist: true }},
+ { keys: 'h', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: false }},
+ { keys: 'l', type: 'motion', motion: 'moveByCharacters', motionArgs: { forward: true }},
+ { keys: 'j', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, linewise: true }},
+ { keys: 'k', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, linewise: true }},
+ { keys: 'gj', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: true }},
+ { keys: 'gk', type: 'motion', motion: 'moveByDisplayLines', motionArgs: { forward: false }},
+ { keys: 'w', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false }},
+ { keys: 'W', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: false, bigWord: true }},
+ { keys: 'e', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, inclusive: true }},
+ { keys: 'E', type: 'motion', motion: 'moveByWords', motionArgs: { forward: true, wordEnd: true, bigWord: true, inclusive: true }},
+ { keys: 'b', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }},
+ { keys: 'B', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false, bigWord: true }},
+ { keys: 'ge', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, inclusive: true }},
+ { keys: 'gE', type: 'motion', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: true, bigWord: true, inclusive: true }},
+ { keys: '{', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: false, toJumplist: true }},
+ { keys: '}', type: 'motion', motion: 'moveByParagraph', motionArgs: { forward: true, toJumplist: true }},
+ { keys: '(', type: 'motion', motion: 'moveBySentence', motionArgs: { forward: false }},
+ { keys: ')', type: 'motion', motion: 'moveBySentence', motionArgs: { forward: true }},
+ { keys: '<C-f>', type: 'motion', motion: 'moveByPage', motionArgs: { forward: true }},
+ { keys: '<C-b>', type: 'motion', motion: 'moveByPage', motionArgs: { forward: false }},
+ { keys: '<C-d>', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: true, explicitRepeat: true }},
+ { keys: '<C-u>', type: 'motion', motion: 'moveByScroll', motionArgs: { forward: false, explicitRepeat: true }},
+ { keys: 'gg', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: false, explicitRepeat: true, linewise: true, toJumplist: true }},
+ { keys: 'G', type: 'motion', motion: 'moveToLineOrEdgeOfDocument', motionArgs: { forward: true, explicitRepeat: true, linewise: true, toJumplist: true }},
+ { keys: '0', type: 'motion', motion: 'moveToStartOfLine' },
+ { keys: '^', type: 'motion', motion: 'moveToFirstNonWhiteSpaceCharacter' },
+ { keys: '+', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true }},
+ { keys: '-', type: 'motion', motion: 'moveByLines', motionArgs: { forward: false, toFirstChar:true }},
+ { keys: '_', type: 'motion', motion: 'moveByLines', motionArgs: { forward: true, toFirstChar:true, repeatOffset:-1 }},
+ { keys: '$', type: 'motion', motion: 'moveToEol', motionArgs: { inclusive: true }},
+ { keys: '%', type: 'motion', motion: 'moveToMatchedSymbol', motionArgs: { inclusive: true, toJumplist: true }},
+ { keys: 'f<character>', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: true , inclusive: true }},
+ { keys: 'F<character>', type: 'motion', motion: 'moveToCharacter', motionArgs: { forward: false }},
+ { keys: 't<character>', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: true, inclusive: true }},
+ { keys: 'T<character>', type: 'motion', motion: 'moveTillCharacter', motionArgs: { forward: false }},
+ { keys: ';', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: true }},
+ { keys: ',', type: 'motion', motion: 'repeatLastCharacterSearch', motionArgs: { forward: false }},
+ { keys: '\'<character>', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true, linewise: true}},
+ { keys: '`<character>', type: 'motion', motion: 'goToMark', motionArgs: {toJumplist: true}},
+ { keys: ']`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true } },
+ { keys: '[`', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false } },
+ { keys: ']\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: true, linewise: true } },
+ { keys: '[\'', type: 'motion', motion: 'jumpToMark', motionArgs: { forward: false, linewise: true } },
+ // the next two aren't motions but must come before more general motion declarations
+ { keys: ']p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true, matchIndent: true}},
+ { keys: '[p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true, matchIndent: true}},
+ { keys: ']<character>', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: true, toJumplist: true}},
+ { keys: '[<character>', type: 'motion', motion: 'moveToSymbol', motionArgs: { forward: false, toJumplist: true}},
+ { keys: '|', type: 'motion', motion: 'moveToColumn'},
+ { keys: 'o', type: 'motion', motion: 'moveToOtherHighlightedEnd', context:'visual'},
+ { keys: 'O', type: 'motion', motion: 'moveToOtherHighlightedEnd', motionArgs: {sameLine: true}, context:'visual'},
+ // Operators
+ { keys: 'd', type: 'operator', operator: 'delete' },
+ { keys: 'y', type: 'operator', operator: 'yank' },
+ { keys: 'c', type: 'operator', operator: 'change' },
+ { keys: '=', type: 'operator', operator: 'indentAuto' },
+ { keys: '>', type: 'operator', operator: 'indent', operatorArgs: { indentRight: true }},
+ { keys: '<', type: 'operator', operator: 'indent', operatorArgs: { indentRight: false }},
+ { keys: 'g~', type: 'operator', operator: 'changeCase' },
+ { keys: 'gu', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, isEdit: true },
+ { keys: 'gU', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, isEdit: true },
+ { keys: 'n', type: 'motion', motion: 'findNext', motionArgs: { forward: true, toJumplist: true }},
+ { keys: 'N', type: 'motion', motion: 'findNext', motionArgs: { forward: false, toJumplist: true }},
+ // Operator-Motion dual commands
+ { keys: 'x', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorMotionArgs: { visualLine: false }},
+ { keys: 'X', type: 'operatorMotion', operator: 'delete', motion: 'moveByCharacters', motionArgs: { forward: false }, operatorMotionArgs: { visualLine: true }},
+ { keys: 'D', type: 'operatorMotion', operator: 'delete', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
+ { keys: 'D', type: 'operator', operator: 'delete', operatorArgs: { linewise: true }, context: 'visual'},
+ { keys: 'Y', type: 'operatorMotion', operator: 'yank', motion: 'expandToLine', motionArgs: { linewise: true }, context: 'normal'},
+ { keys: 'Y', type: 'operator', operator: 'yank', operatorArgs: { linewise: true }, context: 'visual'},
+ { keys: 'C', type: 'operatorMotion', operator: 'change', motion: 'moveToEol', motionArgs: { inclusive: true }, context: 'normal'},
+ { keys: 'C', type: 'operator', operator: 'change', operatorArgs: { linewise: true }, context: 'visual'},
+ { keys: '~', type: 'operatorMotion', operator: 'changeCase', motion: 'moveByCharacters', motionArgs: { forward: true }, operatorArgs: { shouldMoveCursor: true }, context: 'normal'},
+ { keys: '~', type: 'operator', operator: 'changeCase', context: 'visual'},
+ { keys: '<C-w>', type: 'operatorMotion', operator: 'delete', motion: 'moveByWords', motionArgs: { forward: false, wordEnd: false }, context: 'insert' },
+ //ignore C-w in normal mode
+ { keys: '<C-w>', type: 'idle', context: 'normal' },
+ // Actions
+ { keys: '<C-i>', type: 'action', action: 'jumpListWalk', actionArgs: { forward: true }},
+ { keys: '<C-o>', type: 'action', action: 'jumpListWalk', actionArgs: { forward: false }},
+ { keys: '<C-e>', type: 'action', action: 'scroll', actionArgs: { forward: true, linewise: true }},
+ { keys: '<C-y>', type: 'action', action: 'scroll', actionArgs: { forward: false, linewise: true }},
+ { keys: 'a', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'charAfter' }, context: 'normal' },
+ { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'eol' }, context: 'normal' },
+ { keys: 'A', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'endOfSelectedArea' }, context: 'visual' },
+ { keys: 'i', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'inplace' }, context: 'normal' },
+ { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'firstNonBlank'}, context: 'normal' },
+ { keys: 'I', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { insertAt: 'startOfSelectedArea' }, context: 'visual' },
+ { keys: 'o', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: true }, context: 'normal' },
+ { keys: 'O', type: 'action', action: 'newLineAndEnterInsertMode', isEdit: true, interlaceInsertRepeat: true, actionArgs: { after: false }, context: 'normal' },
+ { keys: 'v', type: 'action', action: 'toggleVisualMode' },
+ { keys: 'V', type: 'action', action: 'toggleVisualMode', actionArgs: { linewise: true }},
+ { keys: '<C-v>', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }},
+ { keys: '<C-q>', type: 'action', action: 'toggleVisualMode', actionArgs: { blockwise: true }},
+ { keys: 'gv', type: 'action', action: 'reselectLastSelection' },
+ { keys: 'J', type: 'action', action: 'joinLines', isEdit: true },
+ { keys: 'p', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: true, isEdit: true }},
+ { keys: 'P', type: 'action', action: 'paste', isEdit: true, actionArgs: { after: false, isEdit: true }},
+ { keys: 'r<character>', type: 'action', action: 'replace', isEdit: true },
+ { keys: '@<character>', type: 'action', action: 'replayMacro' },
+ { keys: 'q<character>', type: 'action', action: 'enterMacroRecordMode' },
+ // Handle Replace-mode as a special case of insert mode.
+ { keys: 'R', type: 'action', action: 'enterInsertMode', isEdit: true, actionArgs: { replace: true }},
+ { keys: 'u', type: 'action', action: 'undo', context: 'normal' },
+ { keys: 'u', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: true}, context: 'visual', isEdit: true },
+ { keys: 'U', type: 'operator', operator: 'changeCase', operatorArgs: {toLower: false}, context: 'visual', isEdit: true },
+ { keys: '<C-r>', type: 'action', action: 'redo' },
+ { keys: 'm<character>', type: 'action', action: 'setMark' },
+ { keys: '"<character>', type: 'action', action: 'setRegister' },
+ { keys: 'zz', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }},
+ { keys: 'z.', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'center' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
+ { keys: 'zt', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }},
+ { keys: 'z<CR>', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'top' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
+ { keys: 'z-', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }},
+ { keys: 'zb', type: 'action', action: 'scrollToCursor', actionArgs: { position: 'bottom' }, motion: 'moveToFirstNonWhiteSpaceCharacter' },
+ { keys: '.', type: 'action', action: 'repeatLastEdit' },
+ { keys: '<C-a>', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: true, backtrack: false}},
+ { keys: '<C-x>', type: 'action', action: 'incrementNumberToken', isEdit: true, actionArgs: {increase: false, backtrack: false}},
+ { keys: '<C-t>', type: 'action', action: 'indent', actionArgs: { indentRight: true }, context: 'insert' },
+ { keys: '<C-d>', type: 'action', action: 'indent', actionArgs: { indentRight: false }, context: 'insert' },
+ // Text object motions
+ { keys: 'a<character>', type: 'motion', motion: 'textObjectManipulation' },
+ { keys: 'i<character>', type: 'motion', motion: 'textObjectManipulation', motionArgs: { textObjectInner: true }},
+ // Search
+ { keys: '/', type: 'search', searchArgs: { forward: true, querySrc: 'prompt', toJumplist: true }},
+ { keys: '?', type: 'search', searchArgs: { forward: false, querySrc: 'prompt', toJumplist: true }},
+ { keys: '*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
+ { keys: '#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', wholeWordOnly: true, toJumplist: true }},
+ { keys: 'g*', type: 'search', searchArgs: { forward: true, querySrc: 'wordUnderCursor', toJumplist: true }},
+ { keys: 'g#', type: 'search', searchArgs: { forward: false, querySrc: 'wordUnderCursor', toJumplist: true }},
+ // Ex command
+ { keys: ':', type: 'ex' }
+ ];
+ var defaultKeymapLength = defaultKeymap.length;
+
+ /**
+ * Ex commands
+ * Care must be taken when adding to the default Ex command map. For any
+ * pair of commands that have a shared prefix, at least one of their
+ * shortNames must not match the prefix of the other command.
+ */
+ var defaultExCommandMap = [
+ { name: 'colorscheme', shortName: 'colo' },
+ { name: 'map' },
+ { name: 'imap', shortName: 'im' },
+ { name: 'nmap', shortName: 'nm' },
+ { name: 'vmap', shortName: 'vm' },
+ { name: 'unmap' },
+ { name: 'write', shortName: 'w' },
+ { name: 'undo', shortName: 'u' },
+ { name: 'redo', shortName: 'red' },
+ { name: 'set', shortName: 'se' },
+ { name: 'set', shortName: 'se' },
+ { name: 'setlocal', shortName: 'setl' },
+ { name: 'setglobal', shortName: 'setg' },
+ { name: 'sort', shortName: 'sor' },
+ { name: 'substitute', shortName: 's', possiblyAsync: true },
+ { name: 'nohlsearch', shortName: 'noh' },
+ { name: 'yank', shortName: 'y' },
+ { name: 'delmarks', shortName: 'delm' },
+ { name: 'registers', shortName: 'reg', excludeFromCommandHistory: true },
+ { name: 'global', shortName: 'g' }
+ ];
+
+ var Pos = CodeMirror.Pos;
+
+ var Vim = function() {
+ function enterVimMode(cm) {
+ cm.setOption('disableInput', true);
+ cm.setOption('showCursorWhenSelecting', false);
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
+ cm.on('cursorActivity', onCursorActivity);
+ maybeInitVimState(cm);
+ CodeMirror.on(cm.getInputField(), 'paste', getOnPasteFn(cm));
+ }
+
+ function leaveVimMode(cm) {
+ cm.setOption('disableInput', false);
+ cm.off('cursorActivity', onCursorActivity);
+ CodeMirror.off(cm.getInputField(), 'paste', getOnPasteFn(cm));
+ cm.state.vim = null;
+ }
+
+ function detachVimMap(cm, next) {
+ if (this == CodeMirror.keyMap.vim) {
+ CodeMirror.rmClass(cm.getWrapperElement(), "cm-fat-cursor");
+ if (cm.getOption("inputStyle") == "contenteditable" && document.body.style.caretColor != null) {
+ disableFatCursorMark(cm);
+ cm.getInputField().style.caretColor = "";
+ }
+ }
+
+ if (!next || next.attach != attachVimMap)
+ leaveVimMode(cm);
+ }
+ function attachVimMap(cm, prev) {
+ if (this == CodeMirror.keyMap.vim) {
+ CodeMirror.addClass(cm.getWrapperElement(), "cm-fat-cursor");
+ if (cm.getOption("inputStyle") == "contenteditable" && document.body.style.caretColor != null) {
+ enableFatCursorMark(cm);
+ cm.getInputField().style.caretColor = "transparent";
+ }
+ }
+
+ if (!prev || prev.attach != attachVimMap)
+ enterVimMode(cm);
+ }
+
+ function updateFatCursorMark(cm) {
+ if (!cm.state.fatCursorMarks) return;
+ clearFatCursorMark(cm);
+ var ranges = cm.listSelections(), result = []
+ for (var i = 0; i < ranges.length; i++) {
+ var range = ranges[i]
+ if (range.empty()) {
+ if (range.anchor.ch < cm.getLine(range.anchor.line).length) {
+ result.push(cm.markText(range.anchor, Pos(range.anchor.line, range.anchor.ch + 1),
+ {className: "cm-fat-cursor-mark"}))
+ } else {
+ var widget = document.createElement("span")
+ widget.textContent = "\u00a0"
+ widget.className = "cm-fat-cursor-mark"
+ result.push(cm.setBookmark(range.anchor, {widget: widget}))
+ }
+ }
+ }
+ cm.state.fatCursorMarks = result;
+ }
+
+ function clearFatCursorMark(cm) {
+ var marks = cm.state.fatCursorMarks;
+ if (marks) for (var i = 0; i < marks.length; i++) marks[i].clear();
+ }
+
+ function enableFatCursorMark(cm) {
+ cm.state.fatCursorMarks = [];
+ updateFatCursorMark(cm)
+ cm.on("cursorActivity", updateFatCursorMark)
+ }
+
+ function disableFatCursorMark(cm) {
+ clearFatCursorMark(cm);
+ cm.off("cursorActivity", updateFatCursorMark);
+ // explicitly set fatCursorMarks to null because event listener above
+ // can be invoke after removing it, if off is called from operation
+ cm.state.fatCursorMarks = null;
+ }
+
+ // Deprecated, simply setting the keymap works again.
+ CodeMirror.defineOption('vimMode', false, function(cm, val, prev) {
+ if (val && cm.getOption("keyMap") != "vim")
+ cm.setOption("keyMap", "vim");
+ else if (!val && prev != CodeMirror.Init && /^vim/.test(cm.getOption("keyMap")))
+ cm.setOption("keyMap", "default");
+ });
+
+ function cmKey(key, cm) {
+ if (!cm) { return undefined; }
+ if (this[key]) { return this[key]; }
+ var vimKey = cmKeyToVimKey(key);
+ if (!vimKey) {
+ return false;
+ }
+ var cmd = CodeMirror.Vim.findKey(cm, vimKey);
+ if (typeof cmd == 'function') {
+ CodeMirror.signal(cm, 'vim-keypress', vimKey);
+ }
+ return cmd;
+ }
+
+ var modifiers = {'Shift': 'S', 'Ctrl': 'C', 'Alt': 'A', 'Cmd': 'D', 'Mod': 'A'};
+ var specialKeys = {Enter:'CR',Backspace:'BS',Delete:'Del',Insert:'Ins'};
+ function cmKeyToVimKey(key) {
+ if (key.charAt(0) == '\'') {
+ // Keypress character binding of format "'a'"
+ return key.charAt(1);
+ }
+ var pieces = key.split(/-(?!$)/);
+ var lastPiece = pieces[pieces.length - 1];
+ if (pieces.length == 1 && pieces[0].length == 1) {
+ // No-modifier bindings use literal character bindings above. Skip.
+ return false;
+ } else if (pieces.length == 2 && pieces[0] == 'Shift' && lastPiece.length == 1) {
+ // Ignore Shift+char bindings as they should be handled by literal character.
+ return false;
+ }
+ var hasCharacter = false;
+ for (var i = 0; i < pieces.length; i++) {
+ var piece = pieces[i];
+ if (piece in modifiers) { pieces[i] = modifiers[piece]; }
+ else { hasCharacter = true; }
+ if (piece in specialKeys) { pieces[i] = specialKeys[piece]; }
+ }
+ if (!hasCharacter) {
+ // Vim does not support modifier only keys.
+ return false;
+ }
+ // TODO: Current bindings expect the character to be lower case, but
+ // it looks like vim key notation uses upper case.
+ if (isUpperCase(lastPiece)) {
+ pieces[pieces.length - 1] = lastPiece.toLowerCase();
+ }
+ return '<' + pieces.join('-') + '>';
+ }
+
+ function getOnPasteFn(cm) {
+ var vim = cm.state.vim;
+ if (!vim.onPasteFn) {
+ vim.onPasteFn = function() {
+ if (!vim.insertMode) {
+ cm.setCursor(offsetCursor(cm.getCursor(), 0, 1));
+ actions.enterInsertMode(cm, {}, vim);
+ }
+ };
+ }
+ return vim.onPasteFn;
+ }
+
+ var numberRegex = /[\d]/;
+ var wordCharTest = [CodeMirror.isWordChar, function(ch) {
+ return ch && !CodeMirror.isWordChar(ch) && !/\s/.test(ch);
+ }], bigWordCharTest = [function(ch) {
+ return /\S/.test(ch);
+ }];
+ function makeKeyRange(start, size) {
+ var keys = [];
+ for (var i = start; i < start + size; i++) {
+ keys.push(String.fromCharCode(i));
+ }
+ return keys;
+ }
+ var upperCaseAlphabet = makeKeyRange(65, 26);
+ var lowerCaseAlphabet = makeKeyRange(97, 26);
+ var numbers = makeKeyRange(48, 10);
+ var validMarks = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['<', '>']);
+ var validRegisters = [].concat(upperCaseAlphabet, lowerCaseAlphabet, numbers, ['-', '"', '.', ':', '/']);
+
+ function isLine(cm, line) {
+ return line >= cm.firstLine() && line <= cm.lastLine();
+ }
+ function isLowerCase(k) {
+ return (/^[a-z]$/).test(k);
+ }
+ function isMatchableSymbol(k) {
+ return '()[]{}'.indexOf(k) != -1;
+ }
+ function isNumber(k) {
+ return numberRegex.test(k);
+ }
+ function isUpperCase(k) {
+ return (/^[A-Z]$/).test(k);
+ }
+ function isWhiteSpaceString(k) {
+ return (/^\s*$/).test(k);
+ }
+ function isEndOfSentenceSymbol(k) {
+ return '.?!'.indexOf(k) != -1;
+ }
+ function inArray(val, arr) {
+ for (var i = 0; i < arr.length; i++) {
+ if (arr[i] == val) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ var options = {};
+ function defineOption(name, defaultValue, type, aliases, callback) {
+ if (defaultValue === undefined && !callback) {
+ throw Error('defaultValue is required unless callback is provided');
+ }
+ if (!type) { type = 'string'; }
+ options[name] = {
+ type: type,
+ defaultValue: defaultValue,
+ callback: callback
+ };
+ if (aliases) {
+ for (var i = 0; i < aliases.length; i++) {
+ options[aliases[i]] = options[name];
+ }
+ }
+ if (defaultValue) {
+ setOption(name, defaultValue);
+ }
+ }
+
+ function setOption(name, value, cm, cfg) {
+ var option = options[name];
+ cfg = cfg || {};
+ var scope = cfg.scope;
+ if (!option) {
+ return new Error('Unknown option: ' + name);
+ }
+ if (option.type == 'boolean') {
+ if (value && value !== true) {
+ return new Error('Invalid argument: ' + name + '=' + value);
+ } else if (value !== false) {
+ // Boolean options are set to true if value is not defined.
+ value = true;
+ }
+ }
+ if (option.callback) {
+ if (scope !== 'local') {
+ option.callback(value, undefined);
+ }
+ if (scope !== 'global' && cm) {
+ option.callback(value, cm);
+ }
+ } else {
+ if (scope !== 'local') {
+ option.value = option.type == 'boolean' ? !!value : value;
+ }
+ if (scope !== 'global' && cm) {
+ cm.state.vim.options[name] = {value: value};
+ }
+ }
+ }
+
+ function getOption(name, cm, cfg) {
+ var option = options[name];
+ cfg = cfg || {};
+ var scope = cfg.scope;
+ if (!option) {
+ return new Error('Unknown option: ' + name);
+ }
+ if (option.callback) {
+ var local = cm && option.callback(undefined, cm);
+ if (scope !== 'global' && local !== undefined) {
+ return local;
+ }
+ if (scope !== 'local') {
+ return option.callback();
+ }
+ return;
+ } else {
+ var local = (scope !== 'global') && (cm && cm.state.vim.options[name]);
+ return (local || (scope !== 'local') && option || {}).value;
+ }
+ }
+
+ defineOption('filetype', undefined, 'string', ['ft'], function(name, cm) {
+ // Option is local. Do nothing for global.
+ if (cm === undefined) {
+ return;
+ }
+ // The 'filetype' option proxies to the CodeMirror 'mode' option.
+ if (name === undefined) {
+ var mode = cm.getOption('mode');
+ return mode == 'null' ? '' : mode;
+ } else {
+ var mode = name == '' ? 'null' : name;
+ cm.setOption('mode', mode);
+ }
+ });
+
+ var createCircularJumpList = function() {
+ var size = 100;
+ var pointer = -1;
+ var head = 0;
+ var tail = 0;
+ var buffer = new Array(size);
+ function add(cm, oldCur, newCur) {
+ var current = pointer % size;
+ var curMark = buffer[current];
+ function useNextSlot(cursor) {
+ var next = ++pointer % size;
+ var trashMark = buffer[next];
+ if (trashMark) {
+ trashMark.clear();
+ }
+ buffer[next] = cm.setBookmark(cursor);
+ }
+ if (curMark) {
+ var markPos = curMark.find();
+ // avoid recording redundant cursor position
+ if (markPos && !cursorEqual(markPos, oldCur)) {
+ useNextSlot(oldCur);
+ }
+ } else {
+ useNextSlot(oldCur);
+ }
+ useNextSlot(newCur);
+ head = pointer;
+ tail = pointer - size + 1;
+ if (tail < 0) {
+ tail = 0;
+ }
+ }
+ function move(cm, offset) {
+ pointer += offset;
+ if (pointer > head) {
+ pointer = head;
+ } else if (pointer < tail) {
+ pointer = tail;
+ }
+ var mark = buffer[(size + pointer) % size];
+ // skip marks that are temporarily removed from text buffer
+ if (mark && !mark.find()) {
+ var inc = offset > 0 ? 1 : -1;
+ var newCur;
+ var oldCur = cm.getCursor();
+ do {
+ pointer += inc;
+ mark = buffer[(size + pointer) % size];
+ // skip marks that are the same as current position
+ if (mark &&
+ (newCur = mark.find()) &&
+ !cursorEqual(oldCur, newCur)) {
+ break;
+ }
+ } while (pointer < head && pointer > tail);
+ }
+ return mark;
+ }
+ return {
+ cachedCursor: undefined, //used for # and * jumps
+ add: add,
+ move: move
+ };
+ };
+
+ // Returns an object to track the changes associated insert mode. It
+ // clones the object that is passed in, or creates an empty object one if
+ // none is provided.
+ var createInsertModeChanges = function(c) {
+ if (c) {
+ // Copy construction
+ return {
+ changes: c.changes,
+ expectCursorActivityForChange: c.expectCursorActivityForChange
+ };
+ }
+ return {
+ // Change list
+ changes: [],
+ // Set to true on change, false on cursorActivity.
+ expectCursorActivityForChange: false
+ };
+ };
+
+ function MacroModeState() {
+ this.latestRegister = undefined;
+ this.isPlaying = false;
+ this.isRecording = false;
+ this.replaySearchQueries = [];
+ this.onRecordingDone = undefined;
+ this.lastInsertModeChanges = createInsertModeChanges();
+ }
+ MacroModeState.prototype = {
+ exitMacroRecordMode: function() {
+ var macroModeState = vimGlobalState.macroModeState;
+ if (macroModeState.onRecordingDone) {
+ macroModeState.onRecordingDone(); // close dialog
+ }
+ macroModeState.onRecordingDone = undefined;
+ macroModeState.isRecording = false;
+ },
+ enterMacroRecordMode: function(cm, registerName) {
+ var register =
+ vimGlobalState.registerController.getRegister(registerName);
+ if (register) {
+ register.clear();
+ this.latestRegister = registerName;
+ if (cm.openDialog) {
+ this.onRecordingDone = cm.openDialog(
+ '(recording)['+registerName+']', null, {bottom:true});
+ }
+ this.isRecording = true;
+ }
+ }
+ };
+
+ function maybeInitVimState(cm) {
+ if (!cm.state.vim) {
+ // Store instance state in the CodeMirror object.
+ cm.state.vim = {
+ inputState: new InputState(),
+ // Vim's input state that triggered the last edit, used to repeat
+ // motions and operators with '.'.
+ lastEditInputState: undefined,
+ // Vim's action command before the last edit, used to repeat actions
+ // with '.' and insert mode repeat.
+ lastEditActionCommand: undefined,
+ // When using jk for navigation, if you move from a longer line to a
+ // shorter line, the cursor may clip to the end of the shorter line.
+ // If j is pressed again and cursor goes to the next line, the
+ // cursor should go back to its horizontal position on the longer
+ // line if it can. This is to keep track of the horizontal position.
+ lastHPos: -1,
+ // Doing the same with screen-position for gj/gk
+ lastHSPos: -1,
+ // The last motion command run. Cleared if a non-motion command gets
+ // executed in between.
+ lastMotion: null,
+ marks: {},
+ // Mark for rendering fake cursor for visual mode.
+ fakeCursor: null,
+ insertMode: false,
+ // Repeat count for changes made in insert mode, triggered by key
+ // sequences like 3,i. Only exists when insertMode is true.
+ insertModeRepeat: undefined,
+ visualMode: false,
+ // If we are in visual line mode. No effect if visualMode is false.
+ visualLine: false,
+ visualBlock: false,
+ lastSelection: null,
+ lastPastedText: null,
+ sel: {},
+ // Buffer-local/window-local values of vim options.
+ options: {}
+ };
+ }
+ return cm.state.vim;
+ }
+ var vimGlobalState;
+ function resetVimGlobalState() {
+ vimGlobalState = {
+ // The current search query.
+ searchQuery: null,
+ // Whether we are searching backwards.
+ searchIsReversed: false,
+ // Replace part of the last substituted pattern
+ lastSubstituteReplacePart: undefined,
+ jumpList: createCircularJumpList(),
+ macroModeState: new MacroModeState,
+ // Recording latest f, t, F or T motion command.
+ lastCharacterSearch: {increment:0, forward:true, selectedCharacter:''},
+ registerController: new RegisterController({}),
+ // search history buffer
+ searchHistoryController: new HistoryController(),
+ // ex Command history buffer
+ exCommandHistoryController : new HistoryController()
+ };
+ for (var optionName in options) {
+ var option = options[optionName];
+ option.value = option.defaultValue;
+ }
+ }
+
+ var lastInsertModeKeyTimer;
+ var vimApi= {
+ buildKeyMap: function() {
+ // TODO: Convert keymap into dictionary format for fast lookup.
+ },
+ // Testing hook, though it might be useful to expose the register
+ // controller anyways.
+ getRegisterController: function() {
+ return vimGlobalState.registerController;
+ },
+ // Testing hook.
+ resetVimGlobalState_: resetVimGlobalState,
+
+ // Testing hook.
+ getVimGlobalState_: function() {
+ return vimGlobalState;
+ },
+
+ // Testing hook.
+ maybeInitVimState_: maybeInitVimState,
+
+ suppressErrorLogging: false,
+
+ InsertModeKey: InsertModeKey,
+ map: function(lhs, rhs, ctx) {
+ // Add user defined key bindings.
+ exCommandDispatcher.map(lhs, rhs, ctx);
+ },
+ unmap: function(lhs, ctx) {
+ exCommandDispatcher.unmap(lhs, ctx);
+ },
+ // Non-recursive map function.
+ // NOTE: This will not create mappings to key maps that aren't present
+ // in the default key map. See TODO at bottom of function.
+ noremap: function(lhs, rhs, ctx) {
+ function toCtxArray(ctx) {
+ return ctx ? [ctx] : ['normal', 'insert', 'visual'];
+ }
+ var ctxsToMap = toCtxArray(ctx);
+ // Look through all actual defaults to find a map candidate.
+ var actualLength = defaultKeymap.length, origLength = defaultKeymapLength;
+ for (var i = actualLength - origLength;
+ i < actualLength && ctxsToMap.length;
+ i++) {
+ var mapping = defaultKeymap[i];
+ // Omit mappings that operate in the wrong context(s) and those of invalid type.
+ if (mapping.keys == rhs &&
+ (!ctx || !mapping.context || mapping.context === ctx) &&
+ mapping.type.substr(0, 2) !== 'ex' &&
+ mapping.type.substr(0, 3) !== 'key') {
+ // Make a shallow copy of the original keymap entry.
+ var newMapping = {};
+ for (var key in mapping) {
+ newMapping[key] = mapping[key];
+ }
+ // Modify it point to the new mapping with the proper context.
+ newMapping.keys = lhs;
+ if (ctx && !newMapping.context) {
+ newMapping.context = ctx;
+ }
+ // Add it to the keymap with a higher priority than the original.
+ this._mapCommand(newMapping);
+ // Record the mapped contexts as complete.
+ var mappedCtxs = toCtxArray(mapping.context);
+ ctxsToMap = ctxsToMap.filter(function(el) { return mappedCtxs.indexOf(el) === -1; });
+ }
+ }
+ // TODO: Create non-recursive keyToKey mappings for the unmapped contexts once those exist.
+ },
+ // Remove all user-defined mappings for the provided context.
+ mapclear: function(ctx) {
+ // Partition the existing keymap into user-defined and true defaults.
+ var actualLength = defaultKeymap.length,
+ origLength = defaultKeymapLength;
+ var userKeymap = defaultKeymap.slice(0, actualLength - origLength);
+ defaultKeymap = defaultKeymap.slice(actualLength - origLength);
+ if (ctx) {
+ // If a specific context is being cleared, we need to keep mappings
+ // from all other contexts.
+ for (var i = userKeymap.length - 1; i >= 0; i--) {
+ var mapping = userKeymap[i];
+ if (ctx !== mapping.context) {
+ if (mapping.context) {
+ this._mapCommand(mapping);
+ } else {
+ // `mapping` applies to all contexts so create keymap copies
+ // for each context except the one being cleared.
+ var contexts = ['normal', 'insert', 'visual'];
+ for (var j in contexts) {
+ if (contexts[j] !== ctx) {
+ var newMapping = {};
+ for (var key in mapping) {
+ newMapping[key] = mapping[key];
+ }
+ newMapping.context = contexts[j];
+ this._mapCommand(newMapping);
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ // TODO: Expose setOption and getOption as instance methods. Need to decide how to namespace
+ // them, or somehow make them work with the existing CodeMirror setOption/getOption API.
+ setOption: setOption,
+ getOption: getOption,
+ defineOption: defineOption,
+ defineEx: function(name, prefix, func){
+ if (!prefix) {
+ prefix = name;
+ } else if (name.indexOf(prefix) !== 0) {
+ throw new Error('(Vim.defineEx) "'+prefix+'" is not a prefix of "'+name+'", command not registered');
+ }
+ exCommands[name]=func;
+ exCommandDispatcher.commandMap_[prefix]={name:name, shortName:prefix, type:'api'};
+ },
+ handleKey: function (cm, key, origin) {
+ var command = this.findKey(cm, key, origin);
+ if (typeof command === 'function') {
+ return command();
+ }
+ },
+ /**
+ * This is the outermost function called by CodeMirror, after keys have
+ * been mapped to their Vim equivalents.
+ *
+ * Finds a command based on the key (and cached keys if there is a
+ * multi-key sequence). Returns `undefined` if no key is matched, a noop
+ * function if a partial match is found (multi-key), and a function to
+ * execute the bound command if a a key is matched. The function always
+ * returns true.
+ */
+ findKey: function(cm, key, origin) {
+ var vim = maybeInitVimState(cm);
+ function handleMacroRecording() {
+ var macroModeState = vimGlobalState.macroModeState;
+ if (macroModeState.isRecording) {
+ if (key == 'q') {
+ macroModeState.exitMacroRecordMode();
+ clearInputState(cm);
+ return true;
+ }
+ if (origin != 'mapping') {
+ logKey(macroModeState, key);
+ }
+ }
+ }
+ function handleEsc() {
+ if (key == '<Esc>') {
+ // Clear input state and get back to normal mode.
+ clearInputState(cm);
+ if (vim.visualMode) {
+ exitVisualMode(cm);
+ } else if (vim.insertMode) {
+ exitInsertMode(cm);
+ }
+ return true;
+ }
+ }
+ function doKeyToKey(keys) {
+ // TODO: prevent infinite recursion.
+ var match;
+ while (keys) {
+ // Pull off one command key, which is either a single character
+ // or a special sequence wrapped in '<' and '>', e.g. '<Space>'.
+ match = (/<\w+-.+?>|<\w+>|./).exec(keys);
+ key = match[0];
+ keys = keys.substring(match.index + key.length);
+ CodeMirror.Vim.handleKey(cm, key, 'mapping');
+ }
+ }
+
+ function handleKeyInsertMode() {
+ if (handleEsc()) { return true; }
+ var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;
+ var keysAreChars = key.length == 1;
+ var match = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');
+ // Need to check all key substrings in insert mode.
+ while (keys.length > 1 && match.type != 'full') {
+ var keys = vim.inputState.keyBuffer = keys.slice(1);
+ var thisMatch = commandDispatcher.matchCommand(keys, defaultKeymap, vim.inputState, 'insert');
+ if (thisMatch.type != 'none') { match = thisMatch; }
+ }
+ if (match.type == 'none') { clearInputState(cm); return false; }
+ else if (match.type == 'partial') {
+ if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
+ lastInsertModeKeyTimer = window.setTimeout(
+ function() { if (vim.insertMode && vim.inputState.keyBuffer) { clearInputState(cm); } },
+ getOption('insertModeEscKeysTimeout'));
+ return !keysAreChars;
+ }
+
+ if (lastInsertModeKeyTimer) { window.clearTimeout(lastInsertModeKeyTimer); }
+ if (keysAreChars) {
+ var selections = cm.listSelections();
+ for (var i = 0; i < selections.length; i++) {
+ var here = selections[i].head;
+ cm.replaceRange('', offsetCursor(here, 0, -(keys.length - 1)), here, '+input');
+ }
+ vimGlobalState.macroModeState.lastInsertModeChanges.changes.pop();
+ }
+ clearInputState(cm);
+ return match.command;
+ }
+
+ function handleKeyNonInsertMode() {
+ if (handleMacroRecording() || handleEsc()) { return true; }
+
+ var keys = vim.inputState.keyBuffer = vim.inputState.keyBuffer + key;
+ if (/^[1-9]\d*$/.test(keys)) { return true; }
+
+ var keysMatcher = /^(\d*)(.*)$/.exec(keys);
+ if (!keysMatcher) { clearInputState(cm); return false; }
+ var context = vim.visualMode ? 'visual' :
+ 'normal';
+ var match = commandDispatcher.matchCommand(keysMatcher[2] || keysMatcher[1], defaultKeymap, vim.inputState, context);
+ if (match.type == 'none') { clearInputState(cm); return false; }
+ else if (match.type == 'partial') { return true; }
+
+ vim.inputState.keyBuffer = '';
+ var keysMatcher = /^(\d*)(.*)$/.exec(keys);
+ if (keysMatcher[1] && keysMatcher[1] != '0') {
+ vim.inputState.pushRepeatDigit(keysMatcher[1]);
+ }
+ return match.command;
+ }
+
+ var command;
+ if (vim.insertMode) { command = handleKeyInsertMode(); }
+ else { command = handleKeyNonInsertMode(); }
+ if (command === false) {
+ return !vim.insertMode && key.length === 1 ? function() { return true; } : undefined;
+ } else if (command === true) {
+ // TODO: Look into using CodeMirror's multi-key handling.
+ // Return no-op since we are caching the key. Counts as handled, but
+ // don't want act on it just yet.
+ return function() { return true; };
+ } else {
+ return function() {
+ return cm.operation(function() {
+ cm.curOp.isVimOp = true;
+ try {
+ if (command.type == 'keyToKey') {
+ doKeyToKey(command.toKeys);
+ } else {
+ commandDispatcher.processCommand(cm, vim, command);
+ }
+ } catch (e) {
+ // clear VIM state in case it's in a bad state.
+ cm.state.vim = undefined;
+ maybeInitVimState(cm);
+ if (!CodeMirror.Vim.suppressErrorLogging) {
+ console['log'](e);
+ }
+ throw e;
+ }
+ return true;
+ });
+ };
+ }
+ },
+ handleEx: function(cm, input) {
+ exCommandDispatcher.processCommand(cm, input);
+ },
+
+ defineMotion: defineMotion,
+ defineAction: defineAction,
+ defineOperator: defineOperator,
+ mapCommand: mapCommand,
+ _mapCommand: _mapCommand,
+
+ defineRegister: defineRegister,
+
+ exitVisualMode: exitVisualMode,
+ exitInsertMode: exitInsertMode
+ };
+
+ // Represents the current input state.
+ function InputState() {
+ this.prefixRepeat = [];
+ this.motionRepeat = [];
+
+ this.operator = null;
+ this.operatorArgs = null;
+ this.motion = null;
+ this.motionArgs = null;
+ this.keyBuffer = []; // For matching multi-key commands.
+ this.registerName = null; // Defaults to the unnamed register.
+ }
+ InputState.prototype.pushRepeatDigit = function(n) {
+ if (!this.operator) {
+ this.prefixRepeat = this.prefixRepeat.concat(n);
+ } else {
+ this.motionRepeat = this.motionRepeat.concat(n);
+ }
+ };
+ InputState.prototype.getRepeat = function() {
+ var repeat = 0;
+ if (this.prefixRepeat.length > 0 || this.motionRepeat.length > 0) {
+ repeat = 1;
+ if (this.prefixRepeat.length > 0) {
+ repeat *= parseInt(this.prefixRepeat.join(''), 10);
+ }
+ if (this.motionRepeat.length > 0) {
+ repeat *= parseInt(this.motionRepeat.join(''), 10);
+ }
+ }
+ return repeat;
+ };
+
+ function clearInputState(cm, reason) {
+ cm.state.vim.inputState = new InputState();
+ CodeMirror.signal(cm, 'vim-command-done', reason);
+ }
+
+ /*
+ * Register stores information about copy and paste registers. Besides
+ * text, a register must store whether it is linewise (i.e., when it is
+ * pasted, should it insert itself into a new line, or should the text be
+ * inserted at the cursor position.)
+ */
+ function Register(text, linewise, blockwise) {
+ this.clear();
+ this.keyBuffer = [text || ''];
+ this.insertModeChanges = [];
+ this.searchQueries = [];
+ this.linewise = !!linewise;
+ this.blockwise = !!blockwise;
+ }
+ Register.prototype = {
+ setText: function(text, linewise, blockwise) {
+ this.keyBuffer = [text || ''];
+ this.linewise = !!linewise;
+ this.blockwise = !!blockwise;
+ },
+ pushText: function(text, linewise) {
+ // if this register has ever been set to linewise, use linewise.
+ if (linewise) {
+ if (!this.linewise) {
+ this.keyBuffer.push('\n');
+ }
+ this.linewise = true;
+ }
+ this.keyBuffer.push(text);
+ },
+ pushInsertModeChanges: function(changes) {
+ this.insertModeChanges.push(createInsertModeChanges(changes));
+ },
+ pushSearchQuery: function(query) {
+ this.searchQueries.push(query);
+ },
+ clear: function() {
+ this.keyBuffer = [];
+ this.insertModeChanges = [];
+ this.searchQueries = [];
+ this.linewise = false;
+ },
+ toString: function() {
+ return this.keyBuffer.join('');
+ }
+ };
+
+ /**
+ * Defines an external register.
+ *
+ * The name should be a single character that will be used to reference the register.
+ * The register should support setText, pushText, clear, and toString(). See Register
+ * for a reference implementation.
+ */
+ function defineRegister(name, register) {
+ var registers = vimGlobalState.registerController.registers;
+ if (!name || name.length != 1) {
+ throw Error('Register name must be 1 character');
+ }
+ if (registers[name]) {
+ throw Error('Register already defined ' + name);
+ }
+ registers[name] = register;
+ validRegisters.push(name);
+ }
+
+ /*
+ * vim registers allow you to keep many independent copy and paste buffers.
+ * See http://usevim.com/2012/04/13/registers/ for an introduction.
+ *
+ * RegisterController keeps the state of all the registers. An initial
+ * state may be passed in. The unnamed register '"' will always be
+ * overridden.
+ */
+ function RegisterController(registers) {
+ this.registers = registers;
+ this.unnamedRegister = registers['"'] = new Register();
+ registers['.'] = new Register();
+ registers[':'] = new Register();
+ registers['/'] = new Register();
+ }
+ RegisterController.prototype = {
+ pushText: function(registerName, operator, text, linewise, blockwise) {
+ if (linewise && text.charAt(text.length - 1) !== '\n'){
+ text += '\n';
+ }
+ // Lowercase and uppercase registers refer to the same register.
+ // Uppercase just means append.
+ var register = this.isValidRegister(registerName) ?
+ this.getRegister(registerName) : null;
+ // if no register/an invalid register was specified, things go to the
+ // default registers
+ if (!register) {
+ switch (operator) {
+ case 'yank':
+ // The 0 register contains the text from the most recent yank.
+ this.registers['0'] = new Register(text, linewise, blockwise);
+ break;
+ case 'delete':
+ case 'change':
+ if (text.indexOf('\n') == -1) {
+ // Delete less than 1 line. Update the small delete register.
+ this.registers['-'] = new Register(text, linewise);
+ } else {
+ // Shift down the contents of the numbered registers and put the
+ // deleted text into register 1.
+ this.shiftNumericRegisters_();
+ this.registers['1'] = new Register(text, linewise);
+ }
+ break;
+ }
+ // Make sure the unnamed register is set to what just happened
+ this.unnamedRegister.setText(text, linewise, blockwise);
+ return;
+ }
+
+ // If we've gotten to this point, we've actually specified a register
+ var append = isUpperCase(registerName);
+ if (append) {
+ register.pushText(text, linewise);
+ } else {
+ register.setText(text, linewise, blockwise);
+ }
+ // The unnamed register always has the same value as the last used
+ // register.
+ this.unnamedRegister.setText(register.toString(), linewise);
+ },
+ // Gets the register named @name. If one of @name doesn't already exist,
+ // create it. If @name is invalid, return the unnamedRegister.
+ getRegister: function(name) {
+ if (!this.isValidRegister(name)) {
+ return this.unnamedRegister;
+ }
+ name = name.toLowerCase();
+ if (!this.registers[name]) {
+ this.registers[name] = new Register();
+ }
+ return this.registers[name];
+ },
+ isValidRegister: function(name) {
+ return name && inArray(name, validRegisters);
+ },
+ shiftNumericRegisters_: function() {
+ for (var i = 9; i >= 2; i--) {
+ this.registers[i] = this.getRegister('' + (i - 1));
+ }
+ }
+ };
+ function HistoryController() {
+ this.historyBuffer = [];
+ this.iterator = 0;
+ this.initialPrefix = null;
+ }
+ HistoryController.prototype = {
+ // the input argument here acts a user entered prefix for a small time
+ // until we start autocompletion in which case it is the autocompleted.
+ nextMatch: function (input, up) {
+ var historyBuffer = this.historyBuffer;
+ var dir = up ? -1 : 1;
+ if (this.initialPrefix === null) this.initialPrefix = input;
+ for (var i = this.iterator + dir; up ? i >= 0 : i < historyBuffer.length; i+= dir) {
+ var element = historyBuffer[i];
+ for (var j = 0; j <= element.length; j++) {
+ if (this.initialPrefix == element.substring(0, j)) {
+ this.iterator = i;
+ return element;
+ }
+ }
+ }
+ // should return the user input in case we reach the end of buffer.
+ if (i >= historyBuffer.length) {
+ this.iterator = historyBuffer.length;
+ return this.initialPrefix;
+ }
+ // return the last autocompleted query or exCommand as it is.
+ if (i < 0 ) return input;
+ },
+ pushInput: function(input) {
+ var index = this.historyBuffer.indexOf(input);
+ if (index > -1) this.historyBuffer.splice(index, 1);
+ if (input.length) this.historyBuffer.push(input);
+ },
+ reset: function() {
+ this.initialPrefix = null;
+ this.iterator = this.historyBuffer.length;
+ }
+ };
+ var commandDispatcher = {
+ matchCommand: function(keys, keyMap, inputState, context) {
+ var matches = commandMatches(keys, keyMap, context, inputState);
+ if (!matches.full && !matches.partial) {
+ return {type: 'none'};
+ } else if (!matches.full && matches.partial) {
+ return {type: 'partial'};
+ }
+
+ var bestMatch;
+ for (var i = 0; i < matches.full.length; i++) {
+ var match = matches.full[i];
+ if (!bestMatch) {
+ bestMatch = match;
+ }
+ }
+ if (bestMatch.keys.slice(-11) == '<character>') {
+ var character = lastChar(keys);
+ if (!character) return {type: 'none'};
+ inputState.selectedCharacter = character;
+ }
+ return {type: 'full', command: bestMatch};
+ },
+ processCommand: function(cm, vim, command) {
+ vim.inputState.repeatOverride = command.repeatOverride;
+ switch (command.type) {
+ case 'motion':
+ this.processMotion(cm, vim, command);
+ break;
+ case 'operator':
+ this.processOperator(cm, vim, command);
+ break;
+ case 'operatorMotion':
+ this.processOperatorMotion(cm, vim, command);
+ break;
+ case 'action':
+ this.processAction(cm, vim, command);
+ break;
+ case 'search':
+ this.processSearch(cm, vim, command);
+ break;
+ case 'ex':
+ case 'keyToEx':
+ this.processEx(cm, vim, command);
+ break;
+ default:
+ break;
+ }
+ },
+ processMotion: function(cm, vim, command) {
+ vim.inputState.motion = command.motion;
+ vim.inputState.motionArgs = copyArgs(command.motionArgs);
+ this.evalInput(cm, vim);
+ },
+ processOperator: function(cm, vim, command) {
+ var inputState = vim.inputState;
+ if (inputState.operator) {
+ if (inputState.operator == command.operator) {
+ // Typing an operator twice like 'dd' makes the operator operate
+ // linewise
+ inputState.motion = 'expandToLine';
+ inputState.motionArgs = { linewise: true };
+ this.evalInput(cm, vim);
+ return;
+ } else {
+ // 2 different operators in a row doesn't make sense.
+ clearInputState(cm);
+ }
+ }
+ inputState.operator = command.operator;
+ inputState.operatorArgs = copyArgs(command.operatorArgs);
+ if (vim.visualMode) {
+ // Operating on a selection in visual mode. We don't need a motion.
+ this.evalInput(cm, vim);
+ }
+ },
+ processOperatorMotion: function(cm, vim, command) {
+ var visualMode = vim.visualMode;
+ var operatorMotionArgs = copyArgs(command.operatorMotionArgs);
+ if (operatorMotionArgs) {
+ // Operator motions may have special behavior in visual mode.
+ if (visualMode && operatorMotionArgs.visualLine) {
+ vim.visualLine = true;
+ }
+ }
+ this.processOperator(cm, vim, command);
+ if (!visualMode) {
+ this.processMotion(cm, vim, command);
+ }
+ },
+ processAction: function(cm, vim, command) {
+ var inputState = vim.inputState;
+ var repeat = inputState.getRepeat();
+ var repeatIsExplicit = !!repeat;
+ var actionArgs = copyArgs(command.actionArgs) || {};
+ if (inputState.selectedCharacter) {
+ actionArgs.selectedCharacter = inputState.selectedCharacter;
+ }
+ // Actions may or may not have motions and operators. Do these first.
+ if (command.operator) {
+ this.processOperator(cm, vim, command);
+ }
+ if (command.motion) {
+ this.processMotion(cm, vim, command);
+ }
+ if (command.motion || command.operator) {
+ this.evalInput(cm, vim);
+ }
+ actionArgs.repeat = repeat || 1;
+ actionArgs.repeatIsExplicit = repeatIsExplicit;
+ actionArgs.registerName = inputState.registerName;
+ clearInputState(cm);
+ vim.lastMotion = null;
+ if (command.isEdit) {
+ this.recordLastEdit(vim, inputState, command);
+ }
+ actions[command.action](cm, actionArgs, vim);
+ },
+ processSearch: function(cm, vim, command) {
+ if (!cm.getSearchCursor) {
+ // Search depends on SearchCursor.
+ return;
+ }
+ var forward = command.searchArgs.forward;
+ var wholeWordOnly = command.searchArgs.wholeWordOnly;
+ getSearchState(cm).setReversed(!forward);
+ var promptPrefix = (forward) ? '/' : '?';
+ var originalQuery = getSearchState(cm).getQuery();
+ var originalScrollPos = cm.getScrollInfo();
+ function handleQuery(query, ignoreCase, smartCase) {
+ vimGlobalState.searchHistoryController.pushInput(query);
+ vimGlobalState.searchHistoryController.reset();
+ try {
+ updateSearchQuery(cm, query, ignoreCase, smartCase);
+ } catch (e) {
+ showConfirm(cm, 'Invalid regex: ' + query);
+ clearInputState(cm);
+ return;
+ }
+ commandDispatcher.processMotion(cm, vim, {
+ type: 'motion',
+ motion: 'findNext',
+ motionArgs: { forward: true, toJumplist: command.searchArgs.toJumplist }
+ });
+ }
+ function onPromptClose(query) {
+ cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
+ handleQuery(query, true /** ignoreCase */, true /** smartCase */);
+ var macroModeState = vimGlobalState.macroModeState;
+ if (macroModeState.isRecording) {
+ logSearchQuery(macroModeState, query);
+ }
+ }
+ function onPromptKeyUp(e, query, close) {
+ var keyName = CodeMirror.keyName(e), up, offset;
+ if (keyName == 'Up' || keyName == 'Down') {
+ up = keyName == 'Up' ? true : false;
+ offset = e.target ? e.target.selectionEnd : 0;
+ query = vimGlobalState.searchHistoryController.nextMatch(query, up) || '';
+ close(query);
+ if (offset && e.target) e.target.selectionEnd = e.target.selectionStart = Math.min(offset, e.target.value.length);
+ } else {
+ if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift')
+ vimGlobalState.searchHistoryController.reset();
+ }
+ var parsedQuery;
+ try {
+ parsedQuery = updateSearchQuery(cm, query,
+ true /** ignoreCase */, true /** smartCase */);
+ } catch (e) {
+ // Swallow bad regexes for incremental search.
+ }
+ if (parsedQuery) {
+ cm.scrollIntoView(findNext(cm, !forward, parsedQuery), 30);
+ } else {
+ clearSearchHighlight(cm);
+ cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
+ }
+ }
+ function onPromptKeyDown(e, query, close) {
+ var keyName = CodeMirror.keyName(e);
+ if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' ||
+ (keyName == 'Backspace' && query == '')) {
+ vimGlobalState.searchHistoryController.pushInput(query);
+ vimGlobalState.searchHistoryController.reset();
+ updateSearchQuery(cm, originalQuery);
+ clearSearchHighlight(cm);
+ cm.scrollTo(originalScrollPos.left, originalScrollPos.top);
+ CodeMirror.e_stop(e);
+ clearInputState(cm);
+ close();
+ cm.focus();
+ } else if (keyName == 'Up' || keyName == 'Down') {
+ CodeMirror.e_stop(e);
+ } else if (keyName == 'Ctrl-U') {
+ // Ctrl-U clears input.
+ CodeMirror.e_stop(e);
+ close('');
+ }
+ }
+ switch (command.searchArgs.querySrc) {
+ case 'prompt':
+ var macroModeState = vimGlobalState.macroModeState;
+ if (macroModeState.isPlaying) {
+ var query = macroModeState.replaySearchQueries.shift();
+ handleQuery(query, true /** ignoreCase */, false /** smartCase */);
+ } else {
+ showPrompt(cm, {
+ onClose: onPromptClose,
+ prefix: promptPrefix,
+ desc: searchPromptDesc,
+ onKeyUp: onPromptKeyUp,
+ onKeyDown: onPromptKeyDown
+ });
+ }
+ break;
+ case 'wordUnderCursor':
+ var word = expandWordUnderCursor(cm, false /** inclusive */,
+ true /** forward */, false /** bigWord */,
+ true /** noSymbol */);
+ var isKeyword = true;
+ if (!word) {
+ word = expandWordUnderCursor(cm, false /** inclusive */,
+ true /** forward */, false /** bigWord */,
+ false /** noSymbol */);
+ isKeyword = false;
+ }
+ if (!word) {
+ return;
+ }
+ var query = cm.getLine(word.start.line).substring(word.start.ch,
+ word.end.ch);
+ if (isKeyword && wholeWordOnly) {
+ query = '\\b' + query + '\\b';
+ } else {
+ query = escapeRegex(query);
+ }
+
+ // cachedCursor is used to save the old position of the cursor
+ // when * or # causes vim to seek for the nearest word and shift
+ // the cursor before entering the motion.
+ vimGlobalState.jumpList.cachedCursor = cm.getCursor();
+ cm.setCursor(word.start);
+
+ handleQuery(query, true /** ignoreCase */, false /** smartCase */);
+ break;
+ }
+ },
+ processEx: function(cm, vim, command) {
+ function onPromptClose(input) {
+ // Give the prompt some time to close so that if processCommand shows
+ // an error, the elements don't overlap.
+ vimGlobalState.exCommandHistoryController.pushInput(input);
+ vimGlobalState.exCommandHistoryController.reset();
+ exCommandDispatcher.processCommand(cm, input);
+ }
+ function onPromptKeyDown(e, input, close) {
+ var keyName = CodeMirror.keyName(e), up, offset;
+ if (keyName == 'Esc' || keyName == 'Ctrl-C' || keyName == 'Ctrl-[' ||
+ (keyName == 'Backspace' && input == '')) {
+ vimGlobalState.exCommandHistoryController.pushInput(input);
+ vimGlobalState.exCommandHistoryController.reset();
+ CodeMirror.e_stop(e);
+ clearInputState(cm);
+ close();
+ cm.focus();
+ }
+ if (keyName == 'Up' || keyName == 'Down') {
+ CodeMirror.e_stop(e);
+ up = keyName == 'Up' ? true : false;
+ offset = e.target ? e.target.selectionEnd : 0;
+ input = vimGlobalState.exCommandHistoryController.nextMatch(input, up) || '';
+ close(input);
+ if (offset && e.target) e.target.selectionEnd = e.target.selectionStart = Math.min(offset, e.target.value.length);
+ } else if (keyName == 'Ctrl-U') {
+ // Ctrl-U clears input.
+ CodeMirror.e_stop(e);
+ close('');
+ } else {
+ if ( keyName != 'Left' && keyName != 'Right' && keyName != 'Ctrl' && keyName != 'Alt' && keyName != 'Shift')
+ vimGlobalState.exCommandHistoryController.reset();
+ }
+ }
+ if (command.type == 'keyToEx') {
+ // Handle user defined Ex to Ex mappings
+ exCommandDispatcher.processCommand(cm, command.exArgs.input);
+ } else {
+ if (vim.visualMode) {
+ showPrompt(cm, { onClose: onPromptClose, prefix: ':', value: '\'<,\'>',
+ onKeyDown: onPromptKeyDown, selectValueOnOpen: false});
+ } else {
+ showPrompt(cm, { onClose: onPromptClose, prefix: ':',
+ onKeyDown: onPromptKeyDown});
+ }
+ }
+ },
+ evalInput: function(cm, vim) {
+ // If the motion command is set, execute both the operator and motion.
+ // Otherwise return.
+ var inputState = vim.inputState;
+ var motion = inputState.motion;
+ var motionArgs = inputState.motionArgs || {};
+ var operator = inputState.operator;
+ var operatorArgs = inputState.operatorArgs || {};
+ var registerName = inputState.registerName;
+ var sel = vim.sel;
+ // TODO: Make sure cm and vim selections are identical outside visual mode.
+ var origHead = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.head): cm.getCursor('head'));
+ var origAnchor = copyCursor(vim.visualMode ? clipCursorToContent(cm, sel.anchor) : cm.getCursor('anchor'));
+ var oldHead = copyCursor(origHead);
+ var oldAnchor = copyCursor(origAnchor);
+ var newHead, newAnchor;
+ var repeat;
+ if (operator) {
+ this.recordLastEdit(vim, inputState);
+ }
+ if (inputState.repeatOverride !== undefined) {
+ // If repeatOverride is specified, that takes precedence over the
+ // input state's repeat. Used by Ex mode and can be user defined.
+ repeat = inputState.repeatOverride;
+ } else {
+ repeat = inputState.getRepeat();
+ }
+ if (repeat > 0 && motionArgs.explicitRepeat) {
+ motionArgs.repeatIsExplicit = true;
+ } else if (motionArgs.noRepeat ||
+ (!motionArgs.explicitRepeat && repeat === 0)) {
+ repeat = 1;
+ motionArgs.repeatIsExplicit = false;
+ }
+ if (inputState.selectedCharacter) {
+ // If there is a character input, stick it in all of the arg arrays.
+ motionArgs.selectedCharacter = operatorArgs.selectedCharacter =
+ inputState.selectedCharacter;
+ }
+ motionArgs.repeat = repeat;
+ clearInputState(cm);
+ if (motion) {
+ var motionResult = motions[motion](cm, origHead, motionArgs, vim);
+ vim.lastMotion = motions[motion];
+ if (!motionResult) {
+ return;
+ }
+ if (motionArgs.toJumplist) {
+ var jumpList = vimGlobalState.jumpList;
+ // if the current motion is # or *, use cachedCursor
+ var cachedCursor = jumpList.cachedCursor;
+ if (cachedCursor) {
+ recordJumpPosition(cm, cachedCursor, motionResult);
+ delete jumpList.cachedCursor;
+ } else {
+ recordJumpPosition(cm, origHead, motionResult);
+ }
+ }
+ if (motionResult instanceof Array) {
+ newAnchor = motionResult[0];
+ newHead = motionResult[1];
+ } else {
+ newHead = motionResult;
+ }
+ // TODO: Handle null returns from motion commands better.
+ if (!newHead) {
+ newHead = copyCursor(origHead);
+ }
+ if (vim.visualMode) {
+ if (!(vim.visualBlock && newHead.ch === Infinity)) {
+ newHead = clipCursorToContent(cm, newHead, vim.visualBlock);
+ }
+ if (newAnchor) {
+ newAnchor = clipCursorToContent(cm, newAnchor, true);
+ }
+ newAnchor = newAnchor || oldAnchor;
+ sel.anchor = newAnchor;
+ sel.head = newHead;
+ updateCmSelection(cm);
+ updateMark(cm, vim, '<',
+ cursorIsBefore(newAnchor, newHead) ? newAnchor
+ : newHead);
+ updateMark(cm, vim, '>',
+ cursorIsBefore(newAnchor, newHead) ? newHead
+ : newAnchor);
+ } else if (!operator) {
+ newHead = clipCursorToContent(cm, newHead);
+ cm.setCursor(newHead.line, newHead.ch);
+ }
+ }
+ if (operator) {
+ if (operatorArgs.lastSel) {
+ // Replaying a visual mode operation
+ newAnchor = oldAnchor;
+ var lastSel = operatorArgs.lastSel;
+ var lineOffset = Math.abs(lastSel.head.line - lastSel.anchor.line);
+ var chOffset = Math.abs(lastSel.head.ch - lastSel.anchor.ch);
+ if (lastSel.visualLine) {
+ // Linewise Visual mode: The same number of lines.
+ newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
+ } else if (lastSel.visualBlock) {
+ // Blockwise Visual mode: The same number of lines and columns.
+ newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch + chOffset);
+ } else if (lastSel.head.line == lastSel.anchor.line) {
+ // Normal Visual mode within one line: The same number of characters.
+ newHead = Pos(oldAnchor.line, oldAnchor.ch + chOffset);
+ } else {
+ // Normal Visual mode with several lines: The same number of lines, in the
+ // last line the same number of characters as in the last line the last time.
+ newHead = Pos(oldAnchor.line + lineOffset, oldAnchor.ch);
+ }
+ vim.visualMode = true;
+ vim.visualLine = lastSel.visualLine;
+ vim.visualBlock = lastSel.visualBlock;
+ sel = vim.sel = {
+ anchor: newAnchor,
+ head: newHead
+ };
+ updateCmSelection(cm);
+ } else if (vim.visualMode) {
+ operatorArgs.lastSel = {
+ anchor: copyCursor(sel.anchor),
+ head: copyCursor(sel.head),
+ visualBlock: vim.visualBlock,
+ visualLine: vim.visualLine
+ };
+ }
+ var curStart, curEnd, linewise, mode;
+ var cmSel;
+ if (vim.visualMode) {
+ // Init visual op
+ curStart = cursorMin(sel.head, sel.anchor);
+ curEnd = cursorMax(sel.head, sel.anchor);
+ linewise = vim.visualLine || operatorArgs.linewise;
+ mode = vim.visualBlock ? 'block' :
+ linewise ? 'line' :
+ 'char';
+ cmSel = makeCmSelection(cm, {
+ anchor: curStart,
+ head: curEnd
+ }, mode);
+ if (linewise) {
+ var ranges = cmSel.ranges;
+ if (mode == 'block') {
+ // Linewise operators in visual block mode extend to end of line
+ for (var i = 0; i < ranges.length; i++) {
+ ranges[i].head.ch = lineLength(cm, ranges[i].head.line);
+ }
+ } else if (mode == 'line') {
+ ranges[0].head = Pos(ranges[0].head.line + 1, 0);
+ }
+ }
+ } else {
+ // Init motion op
+ curStart = copyCursor(newAnchor || oldAnchor);
+ curEnd = copyCursor(newHead || oldHead);
+ if (cursorIsBefore(curEnd, curStart)) {
+ var tmp = curStart;
+ curStart = curEnd;
+ curEnd = tmp;
+ }
+ linewise = motionArgs.linewise || operatorArgs.linewise;
+ if (linewise) {
+ // Expand selection to entire line.
+ expandSelectionToLine(cm, curStart, curEnd);
+ } else if (motionArgs.forward) {
+ // Clip to trailing newlines only if the motion goes forward.
+ clipToLine(cm, curStart, curEnd);
+ }
+ mode = 'char';
+ var exclusive = !motionArgs.inclusive || linewise;
+ cmSel = makeCmSelection(cm, {
+ anchor: curStart,
+ head: curEnd
+ }, mode, exclusive);
+ }
+ cm.setSelections(cmSel.ranges, cmSel.primary);
+ vim.lastMotion = null;
+ operatorArgs.repeat = repeat; // For indent in visual mode.
+ operatorArgs.registerName = registerName;
+ // Keep track of linewise as it affects how paste and change behave.
+ operatorArgs.linewise = linewise;
+ var operatorMoveTo = operators[operator](
+ cm, operatorArgs, cmSel.ranges, oldAnchor, newHead);
+ if (vim.visualMode) {
+ exitVisualMode(cm, operatorMoveTo != null);
+ }
+ if (operatorMoveTo) {
+ cm.setCursor(operatorMoveTo);
+ }
+ }
+ },
+ recordLastEdit: function(vim, inputState, actionCommand) {
+ var macroModeState = vimGlobalState.macroModeState;
+ if (macroModeState.isPlaying) { return; }
+ vim.lastEditInputState = inputState;
+ vim.lastEditActionCommand = actionCommand;
+ macroModeState.lastInsertModeChanges.changes = [];
+ macroModeState.lastInsertModeChanges.expectCursorActivityForChange = false;
+ macroModeState.lastInsertModeChanges.visualBlock = vim.visualBlock ? vim.sel.head.line - vim.sel.anchor.line : 0;
+ }
+ };
+
+ /**
+ * typedef {Object{line:number,ch:number}} Cursor An object containing the
+ * position of the cursor.
+ */
+ // All of the functions below return Cursor objects.
+ var motions = {
+ moveToTopLine: function(cm, _head, motionArgs) {
+ var line = getUserVisibleLines(cm).top + motionArgs.repeat -1;
+ return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
+ },
+ moveToMiddleLine: function(cm) {
+ var range = getUserVisibleLines(cm);
+ var line = Math.floor((range.top + range.bottom) * 0.5);
+ return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
+ },
+ moveToBottomLine: function(cm, _head, motionArgs) {
+ var line = getUserVisibleLines(cm).bottom - motionArgs.repeat +1;
+ return Pos(line, findFirstNonWhiteSpaceCharacter(cm.getLine(line)));
+ },
+ expandToLine: function(_cm, head, motionArgs) {
+ // Expands forward to end of line, and then to next line if repeat is
+ // >1. Does not handle backward motion!
+ var cur = head;
+ return Pos(cur.line + motionArgs.repeat - 1, Infinity);
+ },
+ findNext: function(cm, _head, motionArgs) {
+ var state = getSearchState(cm);
+ var query = state.getQuery();
+ if (!query) {
+ return;
+ }
+ var prev = !motionArgs.forward;
+ // If search is initiated with ? instead of /, negate direction.
+ prev = (state.isReversed()) ? !prev : prev;
+ highlightSearchMatches(cm, query);
+ return findNext(cm, prev/** prev */, query, motionArgs.repeat);
+ },
+ goToMark: function(cm, _head, motionArgs, vim) {
+ var pos = getMarkPos(cm, vim, motionArgs.selectedCharacter);
+ if (pos) {
+ return motionArgs.linewise ? { line: pos.line, ch: findFirstNonWhiteSpaceCharacter(cm.getLine(pos.line)) } : pos;
+ }
+ return null;
+ },
+ moveToOtherHighlightedEnd: function(cm, _head, motionArgs, vim) {
+ if (vim.visualBlock && motionArgs.sameLine) {
+ var sel = vim.sel;
+ return [
+ clipCursorToContent(cm, Pos(sel.anchor.line, sel.head.ch)),
+ clipCursorToContent(cm, Pos(sel.head.line, sel.anchor.ch))
+ ];
+ } else {
+ return ([vim.sel.head, vim.sel.anchor]);
+ }
+ },
+ jumpToMark: function(cm, head, motionArgs, vim) {
+ var best = head;
+ for (var i = 0; i < motionArgs.repeat; i++) {
+ var cursor = best;
+ for (var key in vim.marks) {
+ if (!isLowerCase(key)) {
+ continue;
+ }
+ var mark = vim.marks[key].find();
+ var isWrongDirection = (motionArgs.forward) ?
+ cursorIsBefore(mark, cursor) : cursorIsBefore(cursor, mark);
+
+ if (isWrongDirection) {
+ continue;
+ }
+ if (motionArgs.linewise && (mark.line == cursor.line)) {
+ continue;
+ }
+
+ var equal = cursorEqual(cursor, best);
+ var between = (motionArgs.forward) ?
+ cursorIsBetween(cursor, mark, best) :
+ cursorIsBetween(best, mark, cursor);
+
+ if (equal || between) {
+ best = mark;
+ }
+ }
+ }
+
+ if (motionArgs.linewise) {
+ // Vim places the cursor on the first non-whitespace character of
+ // the line if there is one, else it places the cursor at the end
+ // of the line, regardless of whether a mark was found.
+ best = Pos(best.line, findFirstNonWhiteSpaceCharacter(cm.getLine(best.line)));
+ }
+ return best;
+ },
+ moveByCharacters: function(_cm, head, motionArgs) {
+ var cur = head;
+ var repeat = motionArgs.repeat;
+ var ch = motionArgs.forward ? cur.ch + repeat : cur.ch - repeat;
+ return Pos(cur.line, ch);
+ },
+ moveByLines: function(cm, head, motionArgs, vim) {
+ var cur = head;
+ var endCh = cur.ch;
+ // Depending what our last motion was, we may want to do different
+ // things. If our last motion was moving vertically, we want to
+ // preserve the HPos from our last horizontal move. If our last motion
+ // was going to the end of a line, moving vertically we should go to
+ // the end of the line, etc.
+ switch (vim.lastMotion) {
+ case this.moveByLines:
+ case this.moveByDisplayLines:
+ case this.moveByScroll:
+ case this.moveToColumn:
+ case this.moveToEol:
+ endCh = vim.lastHPos;
+ break;
+ default:
+ vim.lastHPos = endCh;
+ }
+ var repeat = motionArgs.repeat+(motionArgs.repeatOffset||0);
+ var line = motionArgs.forward ? cur.line + repeat : cur.line - repeat;
+ var first = cm.firstLine();
+ var last = cm.lastLine();
+ // Vim go to line begin or line end when cursor at first/last line and
+ // move to previous/next line is triggered.
+ if (line < first && cur.line == first){
+ return this.moveToStartOfLine(cm, head, motionArgs, vim);
+ }else if (line > last && cur.line == last){
+ return this.moveToEol(cm, head, motionArgs, vim, true);
+ }
+ if (motionArgs.toFirstChar){
+ endCh=findFirstNonWhiteSpaceCharacter(cm.getLine(line));
+ vim.lastHPos = endCh;
+ }
+ vim.lastHSPos = cm.charCoords(Pos(line, endCh),'div').left;
+ return Pos(line, endCh);
+ },
+ moveByDisplayLines: function(cm, head, motionArgs, vim) {
+ var cur = head;
+ switch (vim.lastMotion) {
+ case this.moveByDisplayLines:
+ case this.moveByScroll:
+ case this.moveByLines:
+ case this.moveToColumn:
+ case this.moveToEol:
+ break;
+ default:
+ vim.lastHSPos = cm.charCoords(cur,'div').left;
+ }
+ var repeat = motionArgs.repeat;
+ var res=cm.findPosV(cur,(motionArgs.forward ? repeat : -repeat),'line',vim.lastHSPos);
+ if (res.hitSide) {
+ if (motionArgs.forward) {
+ var lastCharCoords = cm.charCoords(res, 'div');
+ var goalCoords = { top: lastCharCoords.top + 8, left: vim.lastHSPos };
+ var res = cm.coordsChar(goalCoords, 'div');
+ } else {
+ var resCoords = cm.charCoords(Pos(cm.firstLine(), 0), 'div');
+ resCoords.left = vim.lastHSPos;
+ res = cm.coordsChar(resCoords, 'div');
+ }
+ }
+ vim.lastHPos = res.ch;
+ return res;
+ },
+ moveByPage: function(cm, head, motionArgs) {
+ // CodeMirror only exposes functions that move the cursor page down, so
+ // doing this bad hack to move the cursor and move it back. evalInput
+ // will move the cursor to where it should be in the end.
+ var curStart = head;
+ var repeat = motionArgs.repeat;
+ return cm.findPosV(curStart, (motionArgs.forward ? repeat : -repeat), 'page');
+ },
+ moveByParagraph: function(cm, head, motionArgs) {
+ var dir = motionArgs.forward ? 1 : -1;
+ return findParagraph(cm, head, motionArgs.repeat, dir);
+ },
+ moveBySentence: function(cm, head, motionArgs) {
+ var dir = motionArgs.forward ? 1 : -1;
+ return findSentence(cm, head, motionArgs.repeat, dir);
+ },
+ moveByScroll: function(cm, head, motionArgs, vim) {
+ var scrollbox = cm.getScrollInfo();
+ var curEnd = null;
+ var repeat = motionArgs.repeat;
+ if (!repeat) {
+ repeat = scrollbox.clientHeight / (2 * cm.defaultTextHeight());
+ }
+ var orig = cm.charCoords(head, 'local');
+ motionArgs.repeat = repeat;
+ var curEnd = motions.moveByDisplayLines(cm, head, motionArgs, vim);
+ if (!curEnd) {
+ return null;
+ }
+ var dest = cm.charCoords(curEnd, 'local');
+ cm.scrollTo(null, scrollbox.top + dest.top - orig.top);
+ return curEnd;
+ },
+ moveByWords: function(cm, head, motionArgs) {
+ return moveToWord(cm, head, motionArgs.repeat, !!motionArgs.forward,
+ !!motionArgs.wordEnd, !!motionArgs.bigWord);
+ },
+ moveTillCharacter: function(cm, _head, motionArgs) {
+ var repeat = motionArgs.repeat;
+ var curEnd = moveToCharacter(cm, repeat, motionArgs.forward,
+ motionArgs.selectedCharacter);
+ var increment = motionArgs.forward ? -1 : 1;
+ recordLastCharacterSearch(increment, motionArgs);
+ if (!curEnd) return null;
+ curEnd.ch += increment;
+ return curEnd;
+ },
+ moveToCharacter: function(cm, head, motionArgs) {
+ var repeat = motionArgs.repeat;
+ recordLastCharacterSearch(0, motionArgs);
+ return moveToCharacter(cm, repeat, motionArgs.forward,
+ motionArgs.selectedCharacter) || head;
+ },
+ moveToSymbol: function(cm, head, motionArgs) {
+ var repeat = motionArgs.repeat;
+ return findSymbol(cm, repeat, motionArgs.forward,
+ motionArgs.selectedCharacter) || head;
+ },
+ moveToColumn: function(cm, head, motionArgs, vim) {
+ var repeat = motionArgs.repeat;
+ // repeat is equivalent to which column we want to move to!
+ vim.lastHPos = repeat - 1;
+ vim.lastHSPos = cm.charCoords(head,'div').left;
+ return moveToColumn(cm, repeat);
+ },
+ moveToEol: function(cm, head, motionArgs, vim, keepHPos) {
+ var cur = head;
+ var retval= Pos(cur.line + motionArgs.repeat - 1, Infinity);
+ var end=cm.clipPos(retval);
+ end.ch--;
+ if (!keepHPos) {
+ vim.lastHPos = Infinity;
+ vim.lastHSPos = cm.charCoords(end,'div').left;
+ }
+ return retval;
+ },
+ moveToFirstNonWhiteSpaceCharacter: function(cm, head) {
+ // Go to the start of the line where the text begins, or the end for
+ // whitespace-only lines
+ var cursor = head;
+ return Pos(cursor.line,
+ findFirstNonWhiteSpaceCharacter(cm.getLine(cursor.line)));
+ },
+ moveToMatchedSymbol: function(cm, head) {
+ var cursor = head;
+ var line = cursor.line;
+ var ch = cursor.ch;
+ var lineText = cm.getLine(line);
+ var symbol;
+ for (; ch < lineText.length; ch++) {
+ symbol = lineText.charAt(ch);
+ if (symbol && isMatchableSymbol(symbol)) {
+ var style = cm.getTokenTypeAt(Pos(line, ch + 1));
+ if (style !== "string" && style !== "comment") {
+ break;
+ }
+ }
+ }
+ if (ch < lineText.length) {
+ // Only include angle brackets in analysis if they are being matched.
+ var re = (ch === '<' || ch === '>') ? /[(){}[\]<>]/ : /[(){}[\]]/;
+ var matched = cm.findMatchingBracket(Pos(line, ch), {bracketRegex: re});
+ return matched.to;
+ } else {
+ return cursor;
+ }
+ },
+ moveToStartOfLine: function(_cm, head) {
+ return Pos(head.line, 0);
+ },
+ moveToLineOrEdgeOfDocument: function(cm, _head, motionArgs) {
+ var lineNum = motionArgs.forward ? cm.lastLine() : cm.firstLine();
+ if (motionArgs.repeatIsExplicit) {
+ lineNum = motionArgs.repeat - cm.getOption('firstLineNumber');
+ }
+ return Pos(lineNum,
+ findFirstNonWhiteSpaceCharacter(cm.getLine(lineNum)));
+ },
+ textObjectManipulation: function(cm, head, motionArgs, vim) {
+ // TODO: lots of possible exceptions that can be thrown here. Try da(
+ // outside of a () block.
+ var mirroredPairs = {'(': ')', ')': '(',
+ '{': '}', '}': '{',
+ '[': ']', ']': '[',
+ '<': '>', '>': '<'};
+ var selfPaired = {'\'': true, '"': true, '`': true};
+
+ var character = motionArgs.selectedCharacter;
+ // 'b' refers to '()' block.
+ // 'B' refers to '{}' block.
+ if (character == 'b') {
+ character = '(';
+ } else if (character == 'B') {
+ character = '{';
+ }
+
+ // Inclusive is the difference between a and i
+ // TODO: Instead of using the additional text object map to perform text
+ // object operations, merge the map into the defaultKeyMap and use
+ // motionArgs to define behavior. Define separate entries for 'aw',
+ // 'iw', 'a[', 'i[', etc.
+ var inclusive = !motionArgs.textObjectInner;
+
+ var tmp;
+ if (mirroredPairs[character]) {
+ tmp = selectCompanionObject(cm, head, character, inclusive);
+ } else if (selfPaired[character]) {
+ tmp = findBeginningAndEnd(cm, head, character, inclusive);
+ } else if (character === 'W') {
+ tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
+ true /** bigWord */);
+ } else if (character === 'w') {
+ tmp = expandWordUnderCursor(cm, inclusive, true /** forward */,
+ false /** bigWord */);
+ } else if (character === 'p') {
+ tmp = findParagraph(cm, head, motionArgs.repeat, 0, inclusive);
+ motionArgs.linewise = true;
+ if (vim.visualMode) {
+ if (!vim.visualLine) { vim.visualLine = true; }
+ } else {
+ var operatorArgs = vim.inputState.operatorArgs;
+ if (operatorArgs) { operatorArgs.linewise = true; }
+ tmp.end.line--;
+ }
+ } else {
+ // No text object defined for this, don't move.
+ return null;
+ }
+
+ if (!cm.state.vim.visualMode) {
+ return [tmp.start, tmp.end];
+ } else {
+ return expandSelection(cm, tmp.start, tmp.end);
+ }
+ },
+
+ repeatLastCharacterSearch: function(cm, head, motionArgs) {
+ var lastSearch = vimGlobalState.lastCharacterSearch;
+ var repeat = motionArgs.repeat;
+ var forward = motionArgs.forward === lastSearch.forward;
+ var increment = (lastSearch.increment ? 1 : 0) * (forward ? -1 : 1);
+ cm.moveH(-increment, 'char');
+ motionArgs.inclusive = forward ? true : false;
+ var curEnd = moveToCharacter(cm, repeat, forward, lastSearch.selectedCharacter);
+ if (!curEnd) {
+ cm.moveH(increment, 'char');
+ return head;
+ }
+ curEnd.ch += increment;
+ return curEnd;
+ }
+ };
+
+ function defineMotion(name, fn) {
+ motions[name] = fn;
+ }
+
+ function fillArray(val, times) {
+ var arr = [];
+ for (var i = 0; i < times; i++) {
+ arr.push(val);
+ }
+ return arr;
+ }
+ /**
+ * An operator acts on a text selection. It receives the list of selections
+ * as input. The corresponding CodeMirror selection is guaranteed to
+ * match the input selection.
+ */
+ var operators = {
+ change: function(cm, args, ranges) {
+ var finalHead, text;
+ var vim = cm.state.vim;
+ if (!vim.visualMode) {
+ var anchor = ranges[0].anchor,
+ head = ranges[0].head;
+ text = cm.getRange(anchor, head);
+ var lastState = vim.lastEditInputState || {};
+ if (lastState.motion == "moveByWords" && !isWhiteSpaceString(text)) {
+ // Exclude trailing whitespace if the range is not all whitespace.
+ var match = (/\s+$/).exec(text);
+ if (match && lastState.motionArgs && lastState.motionArgs.forward) {
+ head = offsetCursor(head, 0, - match[0].length);
+ text = text.slice(0, - match[0].length);
+ }
+ }
+ var prevLineEnd = new Pos(anchor.line - 1, Number.MAX_VALUE);
+ var wasLastLine = cm.firstLine() == cm.lastLine();
+ if (head.line > cm.lastLine() && args.linewise && !wasLastLine) {
+ cm.replaceRange('', prevLineEnd, head);
+ } else {
+ cm.replaceRange('', anchor, head);
+ }
+ if (args.linewise) {
+ // Push the next line back down, if there is a next line.
+ if (!wasLastLine) {
+ cm.setCursor(prevLineEnd);
+ CodeMirror.commands.newlineAndIndent(cm);
+ }
+ // make sure cursor ends up at the end of the line.
+ anchor.ch = Number.MAX_VALUE;
+ }
+ finalHead = anchor;
+ } else {
+ text = cm.getSelection();
+ var replacement = fillArray('', ranges.length);
+ cm.replaceSelections(replacement);
+ finalHead = cursorMin(ranges[0].head, ranges[0].anchor);
+ }
+ vimGlobalState.registerController.pushText(
+ args.registerName, 'change', text,
+ args.linewise, ranges.length > 1);
+ actions.enterInsertMode(cm, {head: finalHead}, cm.state.vim);
+ },
+ // delete is a javascript keyword.
+ 'delete': function(cm, args, ranges) {
+ var finalHead, text;
+ var vim = cm.state.vim;
+ if (!vim.visualBlock) {
+ var anchor = ranges[0].anchor,
+ head = ranges[0].head;
+ if (args.linewise &&
+ head.line != cm.firstLine() &&
+ anchor.line == cm.lastLine() &&
+ anchor.line == head.line - 1) {
+ // Special case for dd on last line (and first line).
+ if (anchor.line == cm.firstLine()) {
+ anchor.ch = 0;
+ } else {
+ anchor = Pos(anchor.line - 1, lineLength(cm, anchor.line - 1));
+ }
+ }
+ text = cm.getRange(anchor, head);
+ cm.replaceRange('', anchor, head);
+ finalHead = anchor;
+ if (args.linewise) {
+ finalHead = motions.moveToFirstNonWhiteSpaceCharacter(cm, anchor);
+ }
+ } else {
+ text = cm.getSelection();
+ var replacement = fillArray('', ranges.length);
+ cm.replaceSelections(replacement);
+ finalHead = ranges[0].anchor;
+ }
+ vimGlobalState.registerController.pushText(
+ args.registerName, 'delete', text,
+ args.linewise, vim.visualBlock);
+ var includeLineBreak = vim.insertMode
+ return clipCursorToContent(cm, finalHead, includeLineBreak);
+ },
+ indent: function(cm, args, ranges) {
+ var vim = cm.state.vim;
+ var startLine = ranges[0].anchor.line;
+ var endLine = vim.visualBlock ?
+ ranges[ranges.length - 1].anchor.line :
+ ranges[0].head.line;
+ // In visual mode, n> shifts the selection right n times, instead of
+ // shifting n lines right once.
+ var repeat = (vim.visualMode) ? args.repeat : 1;
+ if (args.linewise) {
+ // The only way to delete a newline is to delete until the start of
+ // the next line, so in linewise mode evalInput will include the next
+ // line. We don't want this in indent, so we go back a line.
+ endLine--;
+ }
+ for (var i = startLine; i <= endLine; i++) {
+ for (var j = 0; j < repeat; j++) {
+ cm.indentLine(i, args.indentRight);
+ }
+ }
+ return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor);
+ },
+ indentAuto: function(cm, _args, ranges) {
+ cm.execCommand("indentAuto");
+ return motions.moveToFirstNonWhiteSpaceCharacter(cm, ranges[0].anchor);
+ },
+ changeCase: function(cm, args, ranges, oldAnchor, newHead) {
+ var selections = cm.getSelections();
+ var swapped = [];
+ var toLower = args.toLower;
+ for (var j = 0; j < selections.length; j++) {
+ var toSwap = selections[j];
+ var text = '';
+ if (toLower === true) {
+ text = toSwap.toLowerCase();
+ } else if (toLower === false) {
+ text = toSwap.toUpperCase();
+ } else {
+ for (var i = 0; i < toSwap.length; i++) {
+ var character = toSwap.charAt(i);
+ text += isUpperCase(character) ? character.toLowerCase() :
+ character.toUpperCase();
+ }
+ }
+ swapped.push(text);
+ }
+ cm.replaceSelections(swapped);
+ if (args.shouldMoveCursor){
+ return newHead;
+ } else if (!cm.state.vim.visualMode && args.linewise && ranges[0].anchor.line + 1 == ranges[0].head.line) {
+ return motions.moveToFirstNonWhiteSpaceCharacter(cm, oldAnchor);
+ } else if (args.linewise){
+ return oldAnchor;
+ } else {
+ return cursorMin(ranges[0].anchor, ranges[0].head);
+ }
+ },
+ yank: function(cm, args, ranges, oldAnchor) {
+ var vim = cm.state.vim;
+ var text = cm.getSelection();
+ var endPos = vim.visualMode
+ ? cursorMin(vim.sel.anchor, vim.sel.head, ranges[0].head, ranges[0].anchor)
+ : oldAnchor;
+ vimGlobalState.registerController.pushText(
+ args.registerName, 'yank',
+ text, args.linewise, vim.visualBlock);
+ return endPos;
+ }
+ };
+
+ function defineOperator(name, fn) {
+ operators[name] = fn;
+ }
+
+ var actions = {
+ jumpListWalk: function(cm, actionArgs, vim) {
+ if (vim.visualMode) {
+ return;
+ }
+ var repeat = actionArgs.repeat;
+ var forward = actionArgs.forward;
+ var jumpList = vimGlobalState.jumpList;
+
+ var mark = jumpList.move(cm, forward ? repeat : -repeat);
+ var markPos = mark ? mark.find() : undefined;
+ markPos = markPos ? markPos : cm.getCursor();
+ cm.setCursor(markPos);
+ },
+ scroll: function(cm, actionArgs, vim) {
+ if (vim.visualMode) {
+ return;
+ }
+ var repeat = actionArgs.repeat || 1;
+ var lineHeight = cm.defaultTextHeight();
+ var top = cm.getScrollInfo().top;
+ var delta = lineHeight * repeat;
+ var newPos = actionArgs.forward ? top + delta : top - delta;
+ var cursor = copyCursor(cm.getCursor());
+ var cursorCoords = cm.charCoords(cursor, 'local');
+ if (actionArgs.forward) {
+ if (newPos > cursorCoords.top) {
+ cursor.line += (newPos - cursorCoords.top) / lineHeight;
+ cursor.line = Math.ceil(cursor.line);
+ cm.setCursor(cursor);
+ cursorCoords = cm.charCoords(cursor, 'local');
+ cm.scrollTo(null, cursorCoords.top);
+ } else {
+ // Cursor stays within bounds. Just reposition the scroll window.
+ cm.scrollTo(null, newPos);
+ }
+ } else {
+ var newBottom = newPos + cm.getScrollInfo().clientHeight;
+ if (newBottom < cursorCoords.bottom) {
+ cursor.line -= (cursorCoords.bottom - newBottom) / lineHeight;
+ cursor.line = Math.floor(cursor.line);
+ cm.setCursor(cursor);
+ cursorCoords = cm.charCoords(cursor, 'local');
+ cm.scrollTo(
+ null, cursorCoords.bottom - cm.getScrollInfo().clientHeight);
+ } else {
+ // Cursor stays within bounds. Just reposition the scroll window.
+ cm.scrollTo(null, newPos);
+ }
+ }
+ },
+ scrollToCursor: function(cm, actionArgs) {
+ var lineNum = cm.getCursor().line;
+ var charCoords = cm.charCoords(Pos(lineNum, 0), 'local');
+ var height = cm.getScrollInfo().clientHeight;
+ var y = charCoords.top;
+ var lineHeight = charCoords.bottom - y;
+ switch (actionArgs.position) {
+ case 'center': y = y - (height / 2) + lineHeight;
+ break;
+ case 'bottom': y = y - height + lineHeight;
+ break;
+ }
+ cm.scrollTo(null, y);
+ },
+ replayMacro: function(cm, actionArgs, vim) {
+ var registerName = actionArgs.selectedCharacter;
+ var repeat = actionArgs.repeat;
+ var macroModeState = vimGlobalState.macroModeState;
+ if (registerName == '@') {
+ registerName = macroModeState.latestRegister;
+ } else {
+ macroModeState.latestRegister = registerName;
+ }
+ while(repeat--){
+ executeMacroRegister(cm, vim, macroModeState, registerName);
+ }
+ },
+ enterMacroRecordMode: function(cm, actionArgs) {
+ var macroModeState = vimGlobalState.macroModeState;
+ var registerName = actionArgs.selectedCharacter;
+ if (vimGlobalState.registerController.isValidRegister(registerName)) {
+ macroModeState.enterMacroRecordMode(cm, registerName);
+ }
+ },
+ toggleOverwrite: function(cm) {
+ if (!cm.state.overwrite) {
+ cm.toggleOverwrite(true);
+ cm.setOption('keyMap', 'vim-replace');
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"});
+ } else {
+ cm.toggleOverwrite(false);
+ cm.setOption('keyMap', 'vim-insert');
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"});
+ }
+ },
+ enterInsertMode: function(cm, actionArgs, vim) {
+ if (cm.getOption('readOnly')) { return; }
+ vim.insertMode = true;
+ vim.insertModeRepeat = actionArgs && actionArgs.repeat || 1;
+ var insertAt = (actionArgs) ? actionArgs.insertAt : null;
+ var sel = vim.sel;
+ var head = actionArgs.head || cm.getCursor('head');
+ var height = cm.listSelections().length;
+ if (insertAt == 'eol') {
+ head = Pos(head.line, lineLength(cm, head.line));
+ } else if (insertAt == 'charAfter') {
+ head = offsetCursor(head, 0, 1);
+ } else if (insertAt == 'firstNonBlank') {
+ head = motions.moveToFirstNonWhiteSpaceCharacter(cm, head);
+ } else if (insertAt == 'startOfSelectedArea') {
+ if (!vim.visualMode)
+ return;
+ if (!vim.visualBlock) {
+ if (sel.head.line < sel.anchor.line) {
+ head = sel.head;
+ } else {
+ head = Pos(sel.anchor.line, 0);
+ }
+ } else {
+ head = Pos(
+ Math.min(sel.head.line, sel.anchor.line),
+ Math.min(sel.head.ch, sel.anchor.ch));
+ height = Math.abs(sel.head.line - sel.anchor.line) + 1;
+ }
+ } else if (insertAt == 'endOfSelectedArea') {
+ if (!vim.visualMode)
+ return;
+ if (!vim.visualBlock) {
+ if (sel.head.line >= sel.anchor.line) {
+ head = offsetCursor(sel.head, 0, 1);
+ } else {
+ head = Pos(sel.anchor.line, 0);
+ }
+ } else {
+ head = Pos(
+ Math.min(sel.head.line, sel.anchor.line),
+ Math.max(sel.head.ch + 1, sel.anchor.ch));
+ height = Math.abs(sel.head.line - sel.anchor.line) + 1;
+ }
+ } else if (insertAt == 'inplace') {
+ if (vim.visualMode){
+ return;
+ }
+ }
+ cm.setOption('disableInput', false);
+ if (actionArgs && actionArgs.replace) {
+ // Handle Replace-mode as a special case of insert mode.
+ cm.toggleOverwrite(true);
+ cm.setOption('keyMap', 'vim-replace');
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "replace"});
+ } else {
+ cm.toggleOverwrite(false);
+ cm.setOption('keyMap', 'vim-insert');
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "insert"});
+ }
+ if (!vimGlobalState.macroModeState.isPlaying) {
+ // Only record if not replaying.
+ cm.on('change', onChange);
+ CodeMirror.on(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
+ }
+ if (vim.visualMode) {
+ exitVisualMode(cm);
+ }
+ selectForInsert(cm, head, height);
+ },
+ toggleVisualMode: function(cm, actionArgs, vim) {
+ var repeat = actionArgs.repeat;
+ var anchor = cm.getCursor();
+ var head;
+ // TODO: The repeat should actually select number of characters/lines
+ // equal to the repeat times the size of the previous visual
+ // operation.
+ if (!vim.visualMode) {
+ // Entering visual mode
+ vim.visualMode = true;
+ vim.visualLine = !!actionArgs.linewise;
+ vim.visualBlock = !!actionArgs.blockwise;
+ head = clipCursorToContent(
+ cm, Pos(anchor.line, anchor.ch + repeat - 1),
+ true /** includeLineBreak */);
+ vim.sel = {
+ anchor: anchor,
+ head: head
+ };
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""});
+ updateCmSelection(cm);
+ updateMark(cm, vim, '<', cursorMin(anchor, head));
+ updateMark(cm, vim, '>', cursorMax(anchor, head));
+ } else if (vim.visualLine ^ actionArgs.linewise ||
+ vim.visualBlock ^ actionArgs.blockwise) {
+ // Toggling between modes
+ vim.visualLine = !!actionArgs.linewise;
+ vim.visualBlock = !!actionArgs.blockwise;
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "visual", subMode: vim.visualLine ? "linewise" : vim.visualBlock ? "blockwise" : ""});
+ updateCmSelection(cm);
+ } else {
+ exitVisualMode(cm);
+ }
+ },
+ reselectLastSelection: function(cm, _actionArgs, vim) {
+ var lastSelection = vim.lastSelection;
+ if (vim.visualMode) {
+ updateLastSelection(cm, vim);
+ }
+ if (lastSelection) {
+ var anchor = lastSelection.anchorMark.find();
+ var head = lastSelection.headMark.find();
+ if (!anchor || !head) {
+ // If the marks have been destroyed due to edits, do nothing.
+ return;
+ }
+ vim.sel = {
+ anchor: anchor,
+ head: head
+ };
+ vim.visualMode = true;
+ vim.visualLine = lastSelection.visualLine;
+ vim.visualBlock = lastSelection.visualBlock;
+ updateCmSelection(cm);
+ updateMark(cm, vim, '<', cursorMin(anchor, head));
+ updateMark(cm, vim, '>', cursorMax(anchor, head));
+ CodeMirror.signal(cm, 'vim-mode-change', {
+ mode: 'visual',
+ subMode: vim.visualLine ? 'linewise' :
+ vim.visualBlock ? 'blockwise' : ''});
+ }
+ },
+ joinLines: function(cm, actionArgs, vim) {
+ var curStart, curEnd;
+ if (vim.visualMode) {
+ curStart = cm.getCursor('anchor');
+ curEnd = cm.getCursor('head');
+ if (cursorIsBefore(curEnd, curStart)) {
+ var tmp = curEnd;
+ curEnd = curStart;
+ curStart = tmp;
+ }
+ curEnd.ch = lineLength(cm, curEnd.line) - 1;
+ } else {
+ // Repeat is the number of lines to join. Minimum 2 lines.
+ var repeat = Math.max(actionArgs.repeat, 2);
+ curStart = cm.getCursor();
+ curEnd = clipCursorToContent(cm, Pos(curStart.line + repeat - 1,
+ Infinity));
+ }
+ var finalCh = 0;
+ for (var i = curStart.line; i < curEnd.line; i++) {
+ finalCh = lineLength(cm, curStart.line);
+ var tmp = Pos(curStart.line + 1,
+ lineLength(cm, curStart.line + 1));
+ var text = cm.getRange(curStart, tmp);
+ text = text.replace(/\n\s*/g, ' ');
+ cm.replaceRange(text, curStart, tmp);
+ }
+ var curFinalPos = Pos(curStart.line, finalCh);
+ if (vim.visualMode) {
+ exitVisualMode(cm, false);
+ }
+ cm.setCursor(curFinalPos);
+ },
+ newLineAndEnterInsertMode: function(cm, actionArgs, vim) {
+ vim.insertMode = true;
+ var insertAt = copyCursor(cm.getCursor());
+ if (insertAt.line === cm.firstLine() && !actionArgs.after) {
+ // Special case for inserting newline before start of document.
+ cm.replaceRange('\n', Pos(cm.firstLine(), 0));
+ cm.setCursor(cm.firstLine(), 0);
+ } else {
+ insertAt.line = (actionArgs.after) ? insertAt.line :
+ insertAt.line - 1;
+ insertAt.ch = lineLength(cm, insertAt.line);
+ cm.setCursor(insertAt);
+ var newlineFn = CodeMirror.commands.newlineAndIndentContinueComment ||
+ CodeMirror.commands.newlineAndIndent;
+ newlineFn(cm);
+ }
+ this.enterInsertMode(cm, { repeat: actionArgs.repeat }, vim);
+ },
+ paste: function(cm, actionArgs, vim) {
+ var cur = copyCursor(cm.getCursor());
+ var register = vimGlobalState.registerController.getRegister(
+ actionArgs.registerName);
+ var text = register.toString();
+ if (!text) {
+ return;
+ }
+ if (actionArgs.matchIndent) {
+ var tabSize = cm.getOption("tabSize");
+ // length that considers tabs and tabSize
+ var whitespaceLength = function(str) {
+ var tabs = (str.split("\t").length - 1);
+ var spaces = (str.split(" ").length - 1);
+ return tabs * tabSize + spaces * 1;
+ };
+ var currentLine = cm.getLine(cm.getCursor().line);
+ var indent = whitespaceLength(currentLine.match(/^\s*/)[0]);
+ // chomp last newline b/c don't want it to match /^\s*/gm
+ var chompedText = text.replace(/\n$/, '');
+ var wasChomped = text !== chompedText;
+ var firstIndent = whitespaceLength(text.match(/^\s*/)[0]);
+ var text = chompedText.replace(/^\s*/gm, function(wspace) {
+ var newIndent = indent + (whitespaceLength(wspace) - firstIndent);
+ if (newIndent < 0) {
+ return "";
+ }
+ else if (cm.getOption("indentWithTabs")) {
+ var quotient = Math.floor(newIndent / tabSize);
+ return Array(quotient + 1).join('\t');
+ }
+ else {
+ return Array(newIndent + 1).join(' ');
+ }
+ });
+ text += wasChomped ? "\n" : "";
+ }
+ if (actionArgs.repeat > 1) {
+ var text = Array(actionArgs.repeat + 1).join(text);
+ }
+ var linewise = register.linewise;
+ var blockwise = register.blockwise;
+ if (blockwise) {
+ text = text.split('\n');
+ if (linewise) {
+ text.pop();
+ }
+ for (var i = 0; i < text.length; i++) {
+ text[i] = (text[i] == '') ? ' ' : text[i];
+ }
+ cur.ch += actionArgs.after ? 1 : 0;
+ cur.ch = Math.min(lineLength(cm, cur.line), cur.ch);
+ } else if (linewise) {
+ if(vim.visualMode) {
+ text = vim.visualLine ? text.slice(0, -1) : '\n' + text.slice(0, text.length - 1) + '\n';
+ } else if (actionArgs.after) {
+ // Move the newline at the end to the start instead, and paste just
+ // before the newline character of the line we are on right now.
+ text = '\n' + text.slice(0, text.length - 1);
+ cur.ch = lineLength(cm, cur.line);
+ } else {
+ cur.ch = 0;
+ }
+ } else {
+ cur.ch += actionArgs.after ? 1 : 0;
+ }
+ var curPosFinal;
+ var idx;
+ if (vim.visualMode) {
+ // save the pasted text for reselection if the need arises
+ vim.lastPastedText = text;
+ var lastSelectionCurEnd;
+ var selectedArea = getSelectedAreaRange(cm, vim);
+ var selectionStart = selectedArea[0];
+ var selectionEnd = selectedArea[1];
+ var selectedText = cm.getSelection();
+ var selections = cm.listSelections();
+ var emptyStrings = new Array(selections.length).join('1').split('1');
+ // save the curEnd marker before it get cleared due to cm.replaceRange.
+ if (vim.lastSelection) {
+ lastSelectionCurEnd = vim.lastSelection.headMark.find();
+ }
+ // push the previously selected text to unnamed register
+ vimGlobalState.registerController.unnamedRegister.setText(selectedText);
+ if (blockwise) {
+ // first delete the selected text
+ cm.replaceSelections(emptyStrings);
+ // Set new selections as per the block length of the yanked text
+ selectionEnd = Pos(selectionStart.line + text.length-1, selectionStart.ch);
+ cm.setCursor(selectionStart);
+ selectBlock(cm, selectionEnd);
+ cm.replaceSelections(text);
+ curPosFinal = selectionStart;
+ } else if (vim.visualBlock) {
+ cm.replaceSelections(emptyStrings);
+ cm.setCursor(selectionStart);
+ cm.replaceRange(text, selectionStart, selectionStart);
+ curPosFinal = selectionStart;
+ } else {
+ cm.replaceRange(text, selectionStart, selectionEnd);
+ curPosFinal = cm.posFromIndex(cm.indexFromPos(selectionStart) + text.length - 1);
+ }
+ // restore the the curEnd marker
+ if(lastSelectionCurEnd) {
+ vim.lastSelection.headMark = cm.setBookmark(lastSelectionCurEnd);
+ }
+ if (linewise) {
+ curPosFinal.ch=0;
+ }
+ } else {
+ if (blockwise) {
+ cm.setCursor(cur);
+ for (var i = 0; i < text.length; i++) {
+ var line = cur.line+i;
+ if (line > cm.lastLine()) {
+ cm.replaceRange('\n', Pos(line, 0));
+ }
+ var lastCh = lineLength(cm, line);
+ if (lastCh < cur.ch) {
+ extendLineToColumn(cm, line, cur.ch);
+ }
+ }
+ cm.setCursor(cur);
+ selectBlock(cm, Pos(cur.line + text.length-1, cur.ch));
+ cm.replaceSelections(text);
+ curPosFinal = cur;
+ } else {
+ cm.replaceRange(text, cur);
+ // Now fine tune the cursor to where we want it.
+ if (linewise && actionArgs.after) {
+ curPosFinal = Pos(
+ cur.line + 1,
+ findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line + 1)));
+ } else if (linewise && !actionArgs.after) {
+ curPosFinal = Pos(
+ cur.line,
+ findFirstNonWhiteSpaceCharacter(cm.getLine(cur.line)));
+ } else if (!linewise && actionArgs.after) {
+ idx = cm.indexFromPos(cur);
+ curPosFinal = cm.posFromIndex(idx + text.length - 1);
+ } else {
+ idx = cm.indexFromPos(cur);
+ curPosFinal = cm.posFromIndex(idx + text.length);
+ }
+ }
+ }
+ if (vim.visualMode) {
+ exitVisualMode(cm, false);
+ }
+ cm.setCursor(curPosFinal);
+ },
+ undo: function(cm, actionArgs) {
+ cm.operation(function() {
+ repeatFn(cm, CodeMirror.commands.undo, actionArgs.repeat)();
+ cm.setCursor(cm.getCursor('anchor'));
+ });
+ },
+ redo: function(cm, actionArgs) {
+ repeatFn(cm, CodeMirror.commands.redo, actionArgs.repeat)();
+ },
+ setRegister: function(_cm, actionArgs, vim) {
+ vim.inputState.registerName = actionArgs.selectedCharacter;
+ },
+ setMark: function(cm, actionArgs, vim) {
+ var markName = actionArgs.selectedCharacter;
+ updateMark(cm, vim, markName, cm.getCursor());
+ },
+ replace: function(cm, actionArgs, vim) {
+ var replaceWith = actionArgs.selectedCharacter;
+ var curStart = cm.getCursor();
+ var replaceTo;
+ var curEnd;
+ var selections = cm.listSelections();
+ if (vim.visualMode) {
+ curStart = cm.getCursor('start');
+ curEnd = cm.getCursor('end');
+ } else {
+ var line = cm.getLine(curStart.line);
+ replaceTo = curStart.ch + actionArgs.repeat;
+ if (replaceTo > line.length) {
+ replaceTo=line.length;
+ }
+ curEnd = Pos(curStart.line, replaceTo);
+ }
+ if (replaceWith=='\n') {
+ if (!vim.visualMode) cm.replaceRange('', curStart, curEnd);
+ // special case, where vim help says to replace by just one line-break
+ (CodeMirror.commands.newlineAndIndentContinueComment || CodeMirror.commands.newlineAndIndent)(cm);
+ } else {
+ var replaceWithStr = cm.getRange(curStart, curEnd);
+ //replace all characters in range by selected, but keep linebreaks
+ replaceWithStr = replaceWithStr.replace(/[^\n]/g, replaceWith);
+ if (vim.visualBlock) {
+ // Tabs are split in visua block before replacing
+ var spaces = new Array(cm.getOption("tabSize")+1).join(' ');
+ replaceWithStr = cm.getSelection();
+ replaceWithStr = replaceWithStr.replace(/\t/g, spaces).replace(/[^\n]/g, replaceWith).split('\n');
+ cm.replaceSelections(replaceWithStr);
+ } else {
+ cm.replaceRange(replaceWithStr, curStart, curEnd);
+ }
+ if (vim.visualMode) {
+ curStart = cursorIsBefore(selections[0].anchor, selections[0].head) ?
+ selections[0].anchor : selections[0].head;
+ cm.setCursor(curStart);
+ exitVisualMode(cm, false);
+ } else {
+ cm.setCursor(offsetCursor(curEnd, 0, -1));
+ }
+ }
+ },
+ incrementNumberToken: function(cm, actionArgs) {
+ var cur = cm.getCursor();
+ var lineStr = cm.getLine(cur.line);
+ var re = /(-?)(?:(0x)([\da-f]+)|(0b|0|)(\d+))/gi;
+ var match;
+ var start;
+ var end;
+ var numberStr;
+ while ((match = re.exec(lineStr)) !== null) {
+ start = match.index;
+ end = start + match[0].length;
+ if (cur.ch < end)break;
+ }
+ if (!actionArgs.backtrack && (end <= cur.ch))return;
+ if (match) {
+ var baseStr = match[2] || match[4]
+ var digits = match[3] || match[5]
+ var increment = actionArgs.increase ? 1 : -1;
+ var base = {'0b': 2, '0': 8, '': 10, '0x': 16}[baseStr.toLowerCase()];
+ var number = parseInt(match[1] + digits, base) + (increment * actionArgs.repeat);
+ numberStr = number.toString(base);
+ var zeroPadding = baseStr ? new Array(digits.length - numberStr.length + 1 + match[1].length).join('0') : ''
+ if (numberStr.charAt(0) === '-') {
+ numberStr = '-' + baseStr + zeroPadding + numberStr.substr(1);
+ } else {
+ numberStr = baseStr + zeroPadding + numberStr;
+ }
+ var from = Pos(cur.line, start);
+ var to = Pos(cur.line, end);
+ cm.replaceRange(numberStr, from, to);
+ } else {
+ return;
+ }
+ cm.setCursor(Pos(cur.line, start + numberStr.length - 1));
+ },
+ repeatLastEdit: function(cm, actionArgs, vim) {
+ var lastEditInputState = vim.lastEditInputState;
+ if (!lastEditInputState) { return; }
+ var repeat = actionArgs.repeat;
+ if (repeat && actionArgs.repeatIsExplicit) {
+ vim.lastEditInputState.repeatOverride = repeat;
+ } else {
+ repeat = vim.lastEditInputState.repeatOverride || repeat;
+ }
+ repeatLastEdit(cm, vim, repeat, false /** repeatForInsert */);
+ },
+ indent: function(cm, actionArgs) {
+ cm.indentLine(cm.getCursor().line, actionArgs.indentRight);
+ },
+ exitInsertMode: exitInsertMode
+ };
+
+ function defineAction(name, fn) {
+ actions[name] = fn;
+ }
+
+ /*
+ * Below are miscellaneous utility functions used by vim.js
+ */
+
+ /**
+ * Clips cursor to ensure that line is within the buffer's range
+ * If includeLineBreak is true, then allow cur.ch == lineLength.
+ */
+ function clipCursorToContent(cm, cur, includeLineBreak) {
+ var line = Math.min(Math.max(cm.firstLine(), cur.line), cm.lastLine() );
+ var maxCh = lineLength(cm, line) - 1;
+ maxCh = (includeLineBreak) ? maxCh + 1 : maxCh;
+ var ch = Math.min(Math.max(0, cur.ch), maxCh);
+ return Pos(line, ch);
+ }
+ function copyArgs(args) {
+ var ret = {};
+ for (var prop in args) {
+ if (args.hasOwnProperty(prop)) {
+ ret[prop] = args[prop];
+ }
+ }
+ return ret;
+ }
+ function offsetCursor(cur, offsetLine, offsetCh) {
+ if (typeof offsetLine === 'object') {
+ offsetCh = offsetLine.ch;
+ offsetLine = offsetLine.line;
+ }
+ return Pos(cur.line + offsetLine, cur.ch + offsetCh);
+ }
+ function commandMatches(keys, keyMap, context, inputState) {
+ // Partial matches are not applied. They inform the key handler
+ // that the current key sequence is a subsequence of a valid key
+ // sequence, so that the key buffer is not cleared.
+ var match, partial = [], full = [];
+ for (var i = 0; i < keyMap.length; i++) {
+ var command = keyMap[i];
+ if (context == 'insert' && command.context != 'insert' ||
+ command.context && command.context != context ||
+ inputState.operator && command.type == 'action' ||
+ !(match = commandMatch(keys, command.keys))) { continue; }
+ if (match == 'partial') { partial.push(command); }
+ if (match == 'full') { full.push(command); }
+ }
+ return {
+ partial: partial.length && partial,
+ full: full.length && full
+ };
+ }
+ function commandMatch(pressed, mapped) {
+ if (mapped.slice(-11) == '<character>') {
+ // Last character matches anything.
+ var prefixLen = mapped.length - 11;
+ var pressedPrefix = pressed.slice(0, prefixLen);
+ var mappedPrefix = mapped.slice(0, prefixLen);
+ return pressedPrefix == mappedPrefix && pressed.length > prefixLen ? 'full' :
+ mappedPrefix.indexOf(pressedPrefix) == 0 ? 'partial' : false;
+ } else {
+ return pressed == mapped ? 'full' :
+ mapped.indexOf(pressed) == 0 ? 'partial' : false;
+ }
+ }
+ function lastChar(keys) {
+ var match = /^.*(<[^>]+>)$/.exec(keys);
+ var selectedCharacter = match ? match[1] : keys.slice(-1);
+ if (selectedCharacter.length > 1){
+ switch(selectedCharacter){
+ case '<CR>':
+ selectedCharacter='\n';
+ break;
+ case '<Space>':
+ selectedCharacter=' ';
+ break;
+ default:
+ selectedCharacter='';
+ break;
+ }
+ }
+ return selectedCharacter;
+ }
+ function repeatFn(cm, fn, repeat) {
+ return function() {
+ for (var i = 0; i < repeat; i++) {
+ fn(cm);
+ }
+ };
+ }
+ function copyCursor(cur) {
+ return Pos(cur.line, cur.ch);
+ }
+ function cursorEqual(cur1, cur2) {
+ return cur1.ch == cur2.ch && cur1.line == cur2.line;
+ }
+ function cursorIsBefore(cur1, cur2) {
+ if (cur1.line < cur2.line) {
+ return true;
+ }
+ if (cur1.line == cur2.line && cur1.ch < cur2.ch) {
+ return true;
+ }
+ return false;
+ }
+ function cursorMin(cur1, cur2) {
+ if (arguments.length > 2) {
+ cur2 = cursorMin.apply(undefined, Array.prototype.slice.call(arguments, 1));
+ }
+ return cursorIsBefore(cur1, cur2) ? cur1 : cur2;
+ }
+ function cursorMax(cur1, cur2) {
+ if (arguments.length > 2) {
+ cur2 = cursorMax.apply(undefined, Array.prototype.slice.call(arguments, 1));
+ }
+ return cursorIsBefore(cur1, cur2) ? cur2 : cur1;
+ }
+ function cursorIsBetween(cur1, cur2, cur3) {
+ // returns true if cur2 is between cur1 and cur3.
+ var cur1before2 = cursorIsBefore(cur1, cur2);
+ var cur2before3 = cursorIsBefore(cur2, cur3);
+ return cur1before2 && cur2before3;
+ }
+ function lineLength(cm, lineNum) {
+ return cm.getLine(lineNum).length;
+ }
+ function trim(s) {
+ if (s.trim) {
+ return s.trim();
+ }
+ return s.replace(/^\s+|\s+$/g, '');
+ }
+ function escapeRegex(s) {
+ return s.replace(/([.?*+$\[\]\/\\(){}|\-])/g, '\\$1');
+ }
+ function extendLineToColumn(cm, lineNum, column) {
+ var endCh = lineLength(cm, lineNum);
+ var spaces = new Array(column-endCh+1).join(' ');
+ cm.setCursor(Pos(lineNum, endCh));
+ cm.replaceRange(spaces, cm.getCursor());
+ }
+ // This functions selects a rectangular block
+ // of text with selectionEnd as any of its corner
+ // Height of block:
+ // Difference in selectionEnd.line and first/last selection.line
+ // Width of the block:
+ // Distance between selectionEnd.ch and any(first considered here) selection.ch
+ function selectBlock(cm, selectionEnd) {
+ var selections = [], ranges = cm.listSelections();
+ var head = copyCursor(cm.clipPos(selectionEnd));
+ var isClipped = !cursorEqual(selectionEnd, head);
+ var curHead = cm.getCursor('head');
+ var primIndex = getIndex(ranges, curHead);
+ var wasClipped = cursorEqual(ranges[primIndex].head, ranges[primIndex].anchor);
+ var max = ranges.length - 1;
+ var index = max - primIndex > primIndex ? max : 0;
+ var base = ranges[index].anchor;
+
+ var firstLine = Math.min(base.line, head.line);
+ var lastLine = Math.max(base.line, head.line);
+ var baseCh = base.ch, headCh = head.ch;
+
+ var dir = ranges[index].head.ch - baseCh;
+ var newDir = headCh - baseCh;
+ if (dir > 0 && newDir <= 0) {
+ baseCh++;
+ if (!isClipped) { headCh--; }
+ } else if (dir < 0 && newDir >= 0) {
+ baseCh--;
+ if (!wasClipped) { headCh++; }
+ } else if (dir < 0 && newDir == -1) {
+ baseCh--;
+ headCh++;
+ }
+ for (var line = firstLine; line <= lastLine; line++) {
+ var range = {anchor: new Pos(line, baseCh), head: new Pos(line, headCh)};
+ selections.push(range);
+ }
+ cm.setSelections(selections);
+ selectionEnd.ch = headCh;
+ base.ch = baseCh;
+ return base;
+ }
+ function selectForInsert(cm, head, height) {
+ var sel = [];
+ for (var i = 0; i < height; i++) {
+ var lineHead = offsetCursor(head, i, 0);
+ sel.push({anchor: lineHead, head: lineHead});
+ }
+ cm.setSelections(sel, 0);
+ }
+ // getIndex returns the index of the cursor in the selections.
+ function getIndex(ranges, cursor, end) {
+ for (var i = 0; i < ranges.length; i++) {
+ var atAnchor = end != 'head' && cursorEqual(ranges[i].anchor, cursor);
+ var atHead = end != 'anchor' && cursorEqual(ranges[i].head, cursor);
+ if (atAnchor || atHead) {
+ return i;
+ }
+ }
+ return -1;
+ }
+ function getSelectedAreaRange(cm, vim) {
+ var lastSelection = vim.lastSelection;
+ var getCurrentSelectedAreaRange = function() {
+ var selections = cm.listSelections();
+ var start = selections[0];
+ var end = selections[selections.length-1];
+ var selectionStart = cursorIsBefore(start.anchor, start.head) ? start.anchor : start.head;
+ var selectionEnd = cursorIsBefore(end.anchor, end.head) ? end.head : end.anchor;
+ return [selectionStart, selectionEnd];
+ };
+ var getLastSelectedAreaRange = function() {
+ var selectionStart = cm.getCursor();
+ var selectionEnd = cm.getCursor();
+ var block = lastSelection.visualBlock;
+ if (block) {
+ var width = block.width;
+ var height = block.height;
+ selectionEnd = Pos(selectionStart.line + height, selectionStart.ch + width);
+ var selections = [];
+ // selectBlock creates a 'proper' rectangular block.
+ // We do not want that in all cases, so we manually set selections.
+ for (var i = selectionStart.line; i < selectionEnd.line; i++) {
+ var anchor = Pos(i, selectionStart.ch);
+ var head = Pos(i, selectionEnd.ch);
+ var range = {anchor: anchor, head: head};
+ selections.push(range);
+ }
+ cm.setSelections(selections);
+ } else {
+ var start = lastSelection.anchorMark.find();
+ var end = lastSelection.headMark.find();
+ var line = end.line - start.line;
+ var ch = end.ch - start.ch;
+ selectionEnd = {line: selectionEnd.line + line, ch: line ? selectionEnd.ch : ch + selectionEnd.ch};
+ if (lastSelection.visualLine) {
+ selectionStart = Pos(selectionStart.line, 0);
+ selectionEnd = Pos(selectionEnd.line, lineLength(cm, selectionEnd.line));
+ }
+ cm.setSelection(selectionStart, selectionEnd);
+ }
+ return [selectionStart, selectionEnd];
+ };
+ if (!vim.visualMode) {
+ // In case of replaying the action.
+ return getLastSelectedAreaRange();
+ } else {
+ return getCurrentSelectedAreaRange();
+ }
+ }
+ // Updates the previous selection with the current selection's values. This
+ // should only be called in visual mode.
+ function updateLastSelection(cm, vim) {
+ var anchor = vim.sel.anchor;
+ var head = vim.sel.head;
+ // To accommodate the effect of lastPastedText in the last selection
+ if (vim.lastPastedText) {
+ head = cm.posFromIndex(cm.indexFromPos(anchor) + vim.lastPastedText.length);
+ vim.lastPastedText = null;
+ }
+ vim.lastSelection = {'anchorMark': cm.setBookmark(anchor),
+ 'headMark': cm.setBookmark(head),
+ 'anchor': copyCursor(anchor),
+ 'head': copyCursor(head),
+ 'visualMode': vim.visualMode,
+ 'visualLine': vim.visualLine,
+ 'visualBlock': vim.visualBlock};
+ }
+ function expandSelection(cm, start, end) {
+ var sel = cm.state.vim.sel;
+ var head = sel.head;
+ var anchor = sel.anchor;
+ var tmp;
+ if (cursorIsBefore(end, start)) {
+ tmp = end;
+ end = start;
+ start = tmp;
+ }
+ if (cursorIsBefore(head, anchor)) {
+ head = cursorMin(start, head);
+ anchor = cursorMax(anchor, end);
+ } else {
+ anchor = cursorMin(start, anchor);
+ head = cursorMax(head, end);
+ head = offsetCursor(head, 0, -1);
+ if (head.ch == -1 && head.line != cm.firstLine()) {
+ head = Pos(head.line - 1, lineLength(cm, head.line - 1));
+ }
+ }
+ return [anchor, head];
+ }
+ /**
+ * Updates the CodeMirror selection to match the provided vim selection.
+ * If no arguments are given, it uses the current vim selection state.
+ */
+ function updateCmSelection(cm, sel, mode) {
+ var vim = cm.state.vim;
+ sel = sel || vim.sel;
+ var mode = mode ||
+ vim.visualLine ? 'line' : vim.visualBlock ? 'block' : 'char';
+ var cmSel = makeCmSelection(cm, sel, mode);
+ cm.setSelections(cmSel.ranges, cmSel.primary);
+ updateFakeCursor(cm);
+ }
+ function makeCmSelection(cm, sel, mode, exclusive) {
+ var head = copyCursor(sel.head);
+ var anchor = copyCursor(sel.anchor);
+ if (mode == 'char') {
+ var headOffset = !exclusive && !cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
+ var anchorOffset = cursorIsBefore(sel.head, sel.anchor) ? 1 : 0;
+ head = offsetCursor(sel.head, 0, headOffset);
+ anchor = offsetCursor(sel.anchor, 0, anchorOffset);
+ return {
+ ranges: [{anchor: anchor, head: head}],
+ primary: 0
+ };
+ } else if (mode == 'line') {
+ if (!cursorIsBefore(sel.head, sel.anchor)) {
+ anchor.ch = 0;
+
+ var lastLine = cm.lastLine();
+ if (head.line > lastLine) {
+ head.line = lastLine;
+ }
+ head.ch = lineLength(cm, head.line);
+ } else {
+ head.ch = 0;
+ anchor.ch = lineLength(cm, anchor.line);
+ }
+ return {
+ ranges: [{anchor: anchor, head: head}],
+ primary: 0
+ };
+ } else if (mode == 'block') {
+ var top = Math.min(anchor.line, head.line),
+ left = Math.min(anchor.ch, head.ch),
+ bottom = Math.max(anchor.line, head.line),
+ right = Math.max(anchor.ch, head.ch) + 1;
+ var height = bottom - top + 1;
+ var primary = head.line == top ? 0 : height - 1;
+ var ranges = [];
+ for (var i = 0; i < height; i++) {
+ ranges.push({
+ anchor: Pos(top + i, left),
+ head: Pos(top + i, right)
+ });
+ }
+ return {
+ ranges: ranges,
+ primary: primary
+ };
+ }
+ }
+ function getHead(cm) {
+ var cur = cm.getCursor('head');
+ if (cm.getSelection().length == 1) {
+ // Small corner case when only 1 character is selected. The "real"
+ // head is the left of head and anchor.
+ cur = cursorMin(cur, cm.getCursor('anchor'));
+ }
+ return cur;
+ }
+
+ /**
+ * If moveHead is set to false, the CodeMirror selection will not be
+ * touched. The caller assumes the responsibility of putting the cursor
+ * in the right place.
+ */
+ function exitVisualMode(cm, moveHead) {
+ var vim = cm.state.vim;
+ if (moveHead !== false) {
+ cm.setCursor(clipCursorToContent(cm, vim.sel.head));
+ }
+ updateLastSelection(cm, vim);
+ vim.visualMode = false;
+ vim.visualLine = false;
+ vim.visualBlock = false;
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
+ if (vim.fakeCursor) {
+ vim.fakeCursor.clear();
+ }
+ }
+
+ // Remove any trailing newlines from the selection. For
+ // example, with the caret at the start of the last word on the line,
+ // 'dw' should word, but not the newline, while 'w' should advance the
+ // caret to the first character of the next line.
+ function clipToLine(cm, curStart, curEnd) {
+ var selection = cm.getRange(curStart, curEnd);
+ // Only clip if the selection ends with trailing newline + whitespace
+ if (/\n\s*$/.test(selection)) {
+ var lines = selection.split('\n');
+ // We know this is all whitespace.
+ lines.pop();
+
+ // Cases:
+ // 1. Last word is an empty line - do not clip the trailing '\n'
+ // 2. Last word is not an empty line - clip the trailing '\n'
+ var line;
+ // Find the line containing the last word, and clip all whitespace up
+ // to it.
+ for (var line = lines.pop(); lines.length > 0 && line && isWhiteSpaceString(line); line = lines.pop()) {
+ curEnd.line--;
+ curEnd.ch = 0;
+ }
+ // If the last word is not an empty line, clip an additional newline
+ if (line) {
+ curEnd.line--;
+ curEnd.ch = lineLength(cm, curEnd.line);
+ } else {
+ curEnd.ch = 0;
+ }
+ }
+ }
+
+ // Expand the selection to line ends.
+ function expandSelectionToLine(_cm, curStart, curEnd) {
+ curStart.ch = 0;
+ curEnd.ch = 0;
+ curEnd.line++;
+ }
+
+ function findFirstNonWhiteSpaceCharacter(text) {
+ if (!text) {
+ return 0;
+ }
+ var firstNonWS = text.search(/\S/);
+ return firstNonWS == -1 ? text.length : firstNonWS;
+ }
+
+ function expandWordUnderCursor(cm, inclusive, _forward, bigWord, noSymbol) {
+ var cur = getHead(cm);
+ var line = cm.getLine(cur.line);
+ var idx = cur.ch;
+
+ // Seek to first word or non-whitespace character, depending on if
+ // noSymbol is true.
+ var test = noSymbol ? wordCharTest[0] : bigWordCharTest [0];
+ while (!test(line.charAt(idx))) {
+ idx++;
+ if (idx >= line.length) { return null; }
+ }
+
+ if (bigWord) {
+ test = bigWordCharTest[0];
+ } else {
+ test = wordCharTest[0];
+ if (!test(line.charAt(idx))) {
+ test = wordCharTest[1];
+ }
+ }
+
+ var end = idx, start = idx;
+ while (test(line.charAt(end)) && end < line.length) { end++; }
+ while (test(line.charAt(start)) && start >= 0) { start--; }
+ start++;
+
+ if (inclusive) {
+ // If present, include all whitespace after word.
+ // Otherwise, include all whitespace before word, except indentation.
+ var wordEnd = end;
+ while (/\s/.test(line.charAt(end)) && end < line.length) { end++; }
+ if (wordEnd == end) {
+ var wordStart = start;
+ while (/\s/.test(line.charAt(start - 1)) && start > 0) { start--; }
+ if (!start) { start = wordStart; }
+ }
+ }
+ return { start: Pos(cur.line, start), end: Pos(cur.line, end) };
+ }
+
+ function recordJumpPosition(cm, oldCur, newCur) {
+ if (!cursorEqual(oldCur, newCur)) {
+ vimGlobalState.jumpList.add(cm, oldCur, newCur);
+ }
+ }
+
+ function recordLastCharacterSearch(increment, args) {
+ vimGlobalState.lastCharacterSearch.increment = increment;
+ vimGlobalState.lastCharacterSearch.forward = args.forward;
+ vimGlobalState.lastCharacterSearch.selectedCharacter = args.selectedCharacter;
+ }
+
+ var symbolToMode = {
+ '(': 'bracket', ')': 'bracket', '{': 'bracket', '}': 'bracket',
+ '[': 'section', ']': 'section',
+ '*': 'comment', '/': 'comment',
+ 'm': 'method', 'M': 'method',
+ '#': 'preprocess'
+ };
+ var findSymbolModes = {
+ bracket: {
+ isComplete: function(state) {
+ if (state.nextCh === state.symb) {
+ state.depth++;
+ if (state.depth >= 1)return true;
+ } else if (state.nextCh === state.reverseSymb) {
+ state.depth--;
+ }
+ return false;
+ }
+ },
+ section: {
+ init: function(state) {
+ state.curMoveThrough = true;
+ state.symb = (state.forward ? ']' : '[') === state.symb ? '{' : '}';
+ },
+ isComplete: function(state) {
+ return state.index === 0 && state.nextCh === state.symb;
+ }
+ },
+ comment: {
+ isComplete: function(state) {
+ var found = state.lastCh === '*' && state.nextCh === '/';
+ state.lastCh = state.nextCh;
+ return found;
+ }
+ },
+ // TODO: The original Vim implementation only operates on level 1 and 2.
+ // The current implementation doesn't check for code block level and
+ // therefore it operates on any levels.
+ method: {
+ init: function(state) {
+ state.symb = (state.symb === 'm' ? '{' : '}');
+ state.reverseSymb = state.symb === '{' ? '}' : '{';
+ },
+ isComplete: function(state) {
+ if (state.nextCh === state.symb)return true;
+ return false;
+ }
+ },
+ preprocess: {
+ init: function(state) {
+ state.index = 0;
+ },
+ isComplete: function(state) {
+ if (state.nextCh === '#') {
+ var token = state.lineText.match(/#(\w+)/)[1];
+ if (token === 'endif') {
+ if (state.forward && state.depth === 0) {
+ return true;
+ }
+ state.depth++;
+ } else if (token === 'if') {
+ if (!state.forward && state.depth === 0) {
+ return true;
+ }
+ state.depth--;
+ }
+ if (token === 'else' && state.depth === 0)return true;
+ }
+ return false;
+ }
+ }
+ };
+ function findSymbol(cm, repeat, forward, symb) {
+ var cur = copyCursor(cm.getCursor());
+ var increment = forward ? 1 : -1;
+ var endLine = forward ? cm.lineCount() : -1;
+ var curCh = cur.ch;
+ var line = cur.line;
+ var lineText = cm.getLine(line);
+ var state = {
+ lineText: lineText,
+ nextCh: lineText.charAt(curCh),
+ lastCh: null,
+ index: curCh,
+ symb: symb,
+ reverseSymb: (forward ? { ')': '(', '}': '{' } : { '(': ')', '{': '}' })[symb],
+ forward: forward,
+ depth: 0,
+ curMoveThrough: false
+ };
+ var mode = symbolToMode[symb];
+ if (!mode)return cur;
+ var init = findSymbolModes[mode].init;
+ var isComplete = findSymbolModes[mode].isComplete;
+ if (init) { init(state); }
+ while (line !== endLine && repeat) {
+ state.index += increment;
+ state.nextCh = state.lineText.charAt(state.index);
+ if (!state.nextCh) {
+ line += increment;
+ state.lineText = cm.getLine(line) || '';
+ if (increment > 0) {
+ state.index = 0;
+ } else {
+ var lineLen = state.lineText.length;
+ state.index = (lineLen > 0) ? (lineLen-1) : 0;
+ }
+ state.nextCh = state.lineText.charAt(state.index);
+ }
+ if (isComplete(state)) {
+ cur.line = line;
+ cur.ch = state.index;
+ repeat--;
+ }
+ }
+ if (state.nextCh || state.curMoveThrough) {
+ return Pos(line, state.index);
+ }
+ return cur;
+ }
+
+ /*
+ * Returns the boundaries of the next word. If the cursor in the middle of
+ * the word, then returns the boundaries of the current word, starting at
+ * the cursor. If the cursor is at the start/end of a word, and we are going
+ * forward/backward, respectively, find the boundaries of the next word.
+ *
+ * @param {CodeMirror} cm CodeMirror object.
+ * @param {Cursor} cur The cursor position.
+ * @param {boolean} forward True to search forward. False to search
+ * backward.
+ * @param {boolean} bigWord True if punctuation count as part of the word.
+ * False if only [a-zA-Z0-9] characters count as part of the word.
+ * @param {boolean} emptyLineIsWord True if empty lines should be treated
+ * as words.
+ * @return {Object{from:number, to:number, line: number}} The boundaries of
+ * the word, or null if there are no more words.
+ */
+ function findWord(cm, cur, forward, bigWord, emptyLineIsWord) {
+ var lineNum = cur.line;
+ var pos = cur.ch;
+ var line = cm.getLine(lineNum);
+ var dir = forward ? 1 : -1;
+ var charTests = bigWord ? bigWordCharTest: wordCharTest;
+
+ if (emptyLineIsWord && line == '') {
+ lineNum += dir;
+ line = cm.getLine(lineNum);
+ if (!isLine(cm, lineNum)) {
+ return null;
+ }
+ pos = (forward) ? 0 : line.length;
+ }
+
+ while (true) {
+ if (emptyLineIsWord && line == '') {
+ return { from: 0, to: 0, line: lineNum };
+ }
+ var stop = (dir > 0) ? line.length : -1;
+ var wordStart = stop, wordEnd = stop;
+ // Find bounds of next word.
+ while (pos != stop) {
+ var foundWord = false;
+ for (var i = 0; i < charTests.length && !foundWord; ++i) {
+ if (charTests[i](line.charAt(pos))) {
+ wordStart = pos;
+ // Advance to end of word.
+ while (pos != stop && charTests[i](line.charAt(pos))) {
+ pos += dir;
+ }
+ wordEnd = pos;
+ foundWord = wordStart != wordEnd;
+ if (wordStart == cur.ch && lineNum == cur.line &&
+ wordEnd == wordStart + dir) {
+ // We started at the end of a word. Find the next one.
+ continue;
+ } else {
+ return {
+ from: Math.min(wordStart, wordEnd + 1),
+ to: Math.max(wordStart, wordEnd),
+ line: lineNum };
+ }
+ }
+ }
+ if (!foundWord) {
+ pos += dir;
+ }
+ }
+ // Advance to next/prev line.
+ lineNum += dir;
+ if (!isLine(cm, lineNum)) {
+ return null;
+ }
+ line = cm.getLine(lineNum);
+ pos = (dir > 0) ? 0 : line.length;
+ }
+ }
+
+ /**
+ * @param {CodeMirror} cm CodeMirror object.
+ * @param {Pos} cur The position to start from.
+ * @param {int} repeat Number of words to move past.
+ * @param {boolean} forward True to search forward. False to search
+ * backward.
+ * @param {boolean} wordEnd True to move to end of word. False to move to
+ * beginning of word.
+ * @param {boolean} bigWord True if punctuation count as part of the word.
+ * False if only alphabet characters count as part of the word.
+ * @return {Cursor} The position the cursor should move to.
+ */
+ function moveToWord(cm, cur, repeat, forward, wordEnd, bigWord) {
+ var curStart = copyCursor(cur);
+ var words = [];
+ if (forward && !wordEnd || !forward && wordEnd) {
+ repeat++;
+ }
+ // For 'e', empty lines are not considered words, go figure.
+ var emptyLineIsWord = !(forward && wordEnd);
+ for (var i = 0; i < repeat; i++) {
+ var word = findWord(cm, cur, forward, bigWord, emptyLineIsWord);
+ if (!word) {
+ var eodCh = lineLength(cm, cm.lastLine());
+ words.push(forward
+ ? {line: cm.lastLine(), from: eodCh, to: eodCh}
+ : {line: 0, from: 0, to: 0});
+ break;
+ }
+ words.push(word);
+ cur = Pos(word.line, forward ? (word.to - 1) : word.from);
+ }
+ var shortCircuit = words.length != repeat;
+ var firstWord = words[0];
+ var lastWord = words.pop();
+ if (forward && !wordEnd) {
+ // w
+ if (!shortCircuit && (firstWord.from != curStart.ch || firstWord.line != curStart.line)) {
+ // We did not start in the middle of a word. Discard the extra word at the end.
+ lastWord = words.pop();
+ }
+ return Pos(lastWord.line, lastWord.from);
+ } else if (forward && wordEnd) {
+ return Pos(lastWord.line, lastWord.to - 1);
+ } else if (!forward && wordEnd) {
+ // ge
+ if (!shortCircuit && (firstWord.to != curStart.ch || firstWord.line != curStart.line)) {
+ // We did not start in the middle of a word. Discard the extra word at the end.
+ lastWord = words.pop();
+ }
+ return Pos(lastWord.line, lastWord.to);
+ } else {
+ // b
+ return Pos(lastWord.line, lastWord.from);
+ }
+ }
+
+ function moveToCharacter(cm, repeat, forward, character) {
+ var cur = cm.getCursor();
+ var start = cur.ch;
+ var idx;
+ for (var i = 0; i < repeat; i ++) {
+ var line = cm.getLine(cur.line);
+ idx = charIdxInLine(start, line, character, forward, true);
+ if (idx == -1) {
+ return null;
+ }
+ start = idx;
+ }
+ return Pos(cm.getCursor().line, idx);
+ }
+
+ function moveToColumn(cm, repeat) {
+ // repeat is always >= 1, so repeat - 1 always corresponds
+ // to the column we want to go to.
+ var line = cm.getCursor().line;
+ return clipCursorToContent(cm, Pos(line, repeat - 1));
+ }
+
+ function updateMark(cm, vim, markName, pos) {
+ if (!inArray(markName, validMarks)) {
+ return;
+ }
+ if (vim.marks[markName]) {
+ vim.marks[markName].clear();
+ }
+ vim.marks[markName] = cm.setBookmark(pos);
+ }
+
+ function charIdxInLine(start, line, character, forward, includeChar) {
+ // Search for char in line.
+ // motion_options: {forward, includeChar}
+ // If includeChar = true, include it too.
+ // If forward = true, search forward, else search backwards.
+ // If char is not found on this line, do nothing
+ var idx;
+ if (forward) {
+ idx = line.indexOf(character, start + 1);
+ if (idx != -1 && !includeChar) {
+ idx -= 1;
+ }
+ } else {
+ idx = line.lastIndexOf(character, start - 1);
+ if (idx != -1 && !includeChar) {
+ idx += 1;
+ }
+ }
+ return idx;
+ }
+
+ function findParagraph(cm, head, repeat, dir, inclusive) {
+ var line = head.line;
+ var min = cm.firstLine();
+ var max = cm.lastLine();
+ var start, end, i = line;
+ function isEmpty(i) { return !cm.getLine(i); }
+ function isBoundary(i, dir, any) {
+ if (any) { return isEmpty(i) != isEmpty(i + dir); }
+ return !isEmpty(i) && isEmpty(i + dir);
+ }
+ if (dir) {
+ while (min <= i && i <= max && repeat > 0) {
+ if (isBoundary(i, dir)) { repeat--; }
+ i += dir;
+ }
+ return new Pos(i, 0);
+ }
+
+ var vim = cm.state.vim;
+ if (vim.visualLine && isBoundary(line, 1, true)) {
+ var anchor = vim.sel.anchor;
+ if (isBoundary(anchor.line, -1, true)) {
+ if (!inclusive || anchor.line != line) {
+ line += 1;
+ }
+ }
+ }
+ var startState = isEmpty(line);
+ for (i = line; i <= max && repeat; i++) {
+ if (isBoundary(i, 1, true)) {
+ if (!inclusive || isEmpty(i) != startState) {
+ repeat--;
+ }
+ }
+ }
+ end = new Pos(i, 0);
+ // select boundary before paragraph for the last one
+ if (i > max && !startState) { startState = true; }
+ else { inclusive = false; }
+ for (i = line; i > min; i--) {
+ if (!inclusive || isEmpty(i) == startState || i == line) {
+ if (isBoundary(i, -1, true)) { break; }
+ }
+ }
+ start = new Pos(i, 0);
+ return { start: start, end: end };
+ }
+
+ function findSentence(cm, cur, repeat, dir) {
+
+ /*
+ Takes an index object
+ {
+ line: the line string,
+ ln: line number,
+ pos: index in line,
+ dir: direction of traversal (-1 or 1)
+ }
+ and modifies the line, ln, and pos members to represent the
+ next valid position or sets them to null if there are
+ no more valid positions.
+ */
+ function nextChar(cm, idx) {
+ if (idx.pos + idx.dir < 0 || idx.pos + idx.dir >= idx.line.length) {
+ idx.ln += idx.dir;
+ if (!isLine(cm, idx.ln)) {
+ idx.line = null;
+ idx.ln = null;
+ idx.pos = null;
+ return;
+ }
+ idx.line = cm.getLine(idx.ln);
+ idx.pos = (idx.dir > 0) ? 0 : idx.line.length - 1;
+ }
+ else {
+ idx.pos += idx.dir;
+ }
+ }
+
+ /*
+ Performs one iteration of traversal in forward direction
+ Returns an index object of the new location
+ */
+ function forward(cm, ln, pos, dir) {
+ var line = cm.getLine(ln);
+ var stop = (line === "");
+
+ var curr = {
+ line: line,
+ ln: ln,
+ pos: pos,
+ dir: dir,
+ }
+
+ var last_valid = {
+ ln: curr.ln,
+ pos: curr.pos,
+ }
+
+ var skip_empty_lines = (curr.line === "");
+
+ // Move one step to skip character we start on
+ nextChar(cm, curr);
+
+ while (curr.line !== null) {
+ last_valid.ln = curr.ln;
+ last_valid.pos = curr.pos;
+
+ if (curr.line === "" && !skip_empty_lines) {
+ return { ln: curr.ln, pos: curr.pos, };
+ }
+ else if (stop && curr.line !== "" && !isWhiteSpaceString(curr.line[curr.pos])) {
+ return { ln: curr.ln, pos: curr.pos, };
+ }
+ else if (isEndOfSentenceSymbol(curr.line[curr.pos])
+ && !stop
+ && (curr.pos === curr.line.length - 1
+ || isWhiteSpaceString(curr.line[curr.pos + 1]))) {
+ stop = true;
+ }
+
+ nextChar(cm, curr);
+ }
+
+ /*
+ Set the position to the last non whitespace character on the last
+ valid line in the case that we reach the end of the document.
+ */
+ var line = cm.getLine(last_valid.ln);
+ last_valid.pos = 0;
+ for(var i = line.length - 1; i >= 0; --i) {
+ if (!isWhiteSpaceString(line[i])) {
+ last_valid.pos = i;
+ break;
+ }
+ }
+
+ return last_valid;
+
+ }
+
+ /*
+ Performs one iteration of traversal in reverse direction
+ Returns an index object of the new location
+ */
+ function reverse(cm, ln, pos, dir) {
+ var line = cm.getLine(ln);
+
+ var curr = {
+ line: line,
+ ln: ln,
+ pos: pos,
+ dir: dir,
+ }
+
+ var last_valid = {
+ ln: curr.ln,
+ pos: null,
+ };
+
+ var skip_empty_lines = (curr.line === "");
+
+ // Move one step to skip character we start on
+ nextChar(cm, curr);
+
+ while (curr.line !== null) {
+
+ if (curr.line === "" && !skip_empty_lines) {
+ if (last_valid.pos !== null) {
+ return last_valid;
+ }
+ else {
+ return { ln: curr.ln, pos: curr.pos };
+ }
+ }
+ else if (isEndOfSentenceSymbol(curr.line[curr.pos])
+ && last_valid.pos !== null
+ && !(curr.ln === last_valid.ln && curr.pos + 1 === last_valid.pos)) {
+ return last_valid;
+ }
+ else if (curr.line !== "" && !isWhiteSpaceString(curr.line[curr.pos])) {
+ skip_empty_lines = false;
+ last_valid = { ln: curr.ln, pos: curr.pos }
+ }
+
+ nextChar(cm, curr);
+ }
+
+ /*
+ Set the position to the first non whitespace character on the last
+ valid line in the case that we reach the beginning of the document.
+ */
+ var line = cm.getLine(last_valid.ln);
+ last_valid.pos = 0;
+ for(var i = 0; i < line.length; ++i) {
+ if (!isWhiteSpaceString(line[i])) {
+ last_valid.pos = i;
+ break;
+ }
+ }
+ return last_valid;
+ }
+
+ var curr_index = {
+ ln: cur.line,
+ pos: cur.ch,
+ };
+
+ while (repeat > 0) {
+ if (dir < 0) {
+ curr_index = reverse(cm, curr_index.ln, curr_index.pos, dir);
+ }
+ else {
+ curr_index = forward(cm, curr_index.ln, curr_index.pos, dir);
+ }
+ repeat--;
+ }
+
+ return Pos(curr_index.ln, curr_index.pos);
+ }
+
+ // TODO: perhaps this finagling of start and end positions belonds
+ // in codemirror/replaceRange?
+ function selectCompanionObject(cm, head, symb, inclusive) {
+ var cur = head, start, end;
+
+ var bracketRegexp = ({
+ '(': /[()]/, ')': /[()]/,
+ '[': /[[\]]/, ']': /[[\]]/,
+ '{': /[{}]/, '}': /[{}]/,
+ '<': /[<>]/, '>': /[<>]/})[symb];
+ var openSym = ({
+ '(': '(', ')': '(',
+ '[': '[', ']': '[',
+ '{': '{', '}': '{',
+ '<': '<', '>': '<'})[symb];
+ var curChar = cm.getLine(cur.line).charAt(cur.ch);
+ // Due to the behavior of scanForBracket, we need to add an offset if the
+ // cursor is on a matching open bracket.
+ var offset = curChar === openSym ? 1 : 0;
+
+ start = cm.scanForBracket(Pos(cur.line, cur.ch + offset), -1, undefined, {'bracketRegex': bracketRegexp});
+ end = cm.scanForBracket(Pos(cur.line, cur.ch + offset), 1, undefined, {'bracketRegex': bracketRegexp});
+
+ if (!start || !end) {
+ return { start: cur, end: cur };
+ }
+
+ start = start.pos;
+ end = end.pos;
+
+ if ((start.line == end.line && start.ch > end.ch)
+ || (start.line > end.line)) {
+ var tmp = start;
+ start = end;
+ end = tmp;
+ }
+
+ if (inclusive) {
+ end.ch += 1;
+ } else {
+ start.ch += 1;
+ }
+
+ return { start: start, end: end };
+ }
+
+ // Takes in a symbol and a cursor and tries to simulate text objects that
+ // have identical opening and closing symbols
+ // TODO support across multiple lines
+ function findBeginningAndEnd(cm, head, symb, inclusive) {
+ var cur = copyCursor(head);
+ var line = cm.getLine(cur.line);
+ var chars = line.split('');
+ var start, end, i, len;
+ var firstIndex = chars.indexOf(symb);
+
+ // the decision tree is to always look backwards for the beginning first,
+ // but if the cursor is in front of the first instance of the symb,
+ // then move the cursor forward
+ if (cur.ch < firstIndex) {
+ cur.ch = firstIndex;
+ // Why is this line even here???
+ // cm.setCursor(cur.line, firstIndex+1);
+ }
+ // otherwise if the cursor is currently on the closing symbol
+ else if (firstIndex < cur.ch && chars[cur.ch] == symb) {
+ end = cur.ch; // assign end to the current cursor
+ --cur.ch; // make sure to look backwards
+ }
+
+ // if we're currently on the symbol, we've got a start
+ if (chars[cur.ch] == symb && !end) {
+ start = cur.ch + 1; // assign start to ahead of the cursor
+ } else {
+ // go backwards to find the start
+ for (i = cur.ch; i > -1 && !start; i--) {
+ if (chars[i] == symb) {
+ start = i + 1;
+ }
+ }
+ }
+
+ // look forwards for the end symbol
+ if (start && !end) {
+ for (i = start, len = chars.length; i < len && !end; i++) {
+ if (chars[i] == symb) {
+ end = i;
+ }
+ }
+ }
+
+ // nothing found
+ if (!start || !end) {
+ return { start: cur, end: cur };
+ }
+
+ // include the symbols
+ if (inclusive) {
+ --start; ++end;
+ }
+
+ return {
+ start: Pos(cur.line, start),
+ end: Pos(cur.line, end)
+ };
+ }
+
+ // Search functions
+ defineOption('pcre', true, 'boolean');
+ function SearchState() {}
+ SearchState.prototype = {
+ getQuery: function() {
+ return vimGlobalState.query;
+ },
+ setQuery: function(query) {
+ vimGlobalState.query = query;
+ },
+ getOverlay: function() {
+ return this.searchOverlay;
+ },
+ setOverlay: function(overlay) {
+ this.searchOverlay = overlay;
+ },
+ isReversed: function() {
+ return vimGlobalState.isReversed;
+ },
+ setReversed: function(reversed) {
+ vimGlobalState.isReversed = reversed;
+ },
+ getScrollbarAnnotate: function() {
+ return this.annotate;
+ },
+ setScrollbarAnnotate: function(annotate) {
+ this.annotate = annotate;
+ }
+ };
+ function getSearchState(cm) {
+ var vim = cm.state.vim;
+ return vim.searchState_ || (vim.searchState_ = new SearchState());
+ }
+ function dialog(cm, template, shortText, onClose, options) {
+ if (cm.openDialog) {
+ cm.openDialog(template, onClose, { bottom: true, value: options.value,
+ onKeyDown: options.onKeyDown, onKeyUp: options.onKeyUp,
+ selectValueOnOpen: false});
+ }
+ else {
+ onClose(prompt(shortText, ''));
+ }
+ }
+ function splitBySlash(argString) {
+ return splitBySeparator(argString, '/');
+ }
+
+ function findUnescapedSlashes(argString) {
+ return findUnescapedSeparators(argString, '/');
+ }
+
+ function splitBySeparator(argString, separator) {
+ var slashes = findUnescapedSeparators(argString, separator) || [];
+ if (!slashes.length) return [];
+ var tokens = [];
+ // in case of strings like foo/bar
+ if (slashes[0] !== 0) return;
+ for (var i = 0; i < slashes.length; i++) {
+ if (typeof slashes[i] == 'number')
+ tokens.push(argString.substring(slashes[i] + 1, slashes[i+1]));
+ }
+ return tokens;
+ }
+
+ function findUnescapedSeparators(str, separator) {
+ if (!separator)
+ separator = '/';
+
+ var escapeNextChar = false;
+ var slashes = [];
+ for (var i = 0; i < str.length; i++) {
+ var c = str.charAt(i);
+ if (!escapeNextChar && c == separator) {
+ slashes.push(i);
+ }
+ escapeNextChar = !escapeNextChar && (c == '\\');
+ }
+ return slashes;
+ }
+
+ // Translates a search string from ex (vim) syntax into javascript form.
+ function translateRegex(str) {
+ // When these match, add a '\' if unescaped or remove one if escaped.
+ var specials = '|(){';
+ // Remove, but never add, a '\' for these.
+ var unescape = '}';
+ var escapeNextChar = false;
+ var out = [];
+ for (var i = -1; i < str.length; i++) {
+ var c = str.charAt(i) || '';
+ var n = str.charAt(i+1) || '';
+ var specialComesNext = (n && specials.indexOf(n) != -1);
+ if (escapeNextChar) {
+ if (c !== '\\' || !specialComesNext) {
+ out.push(c);
+ }
+ escapeNextChar = false;
+ } else {
+ if (c === '\\') {
+ escapeNextChar = true;
+ // Treat the unescape list as special for removing, but not adding '\'.
+ if (n && unescape.indexOf(n) != -1) {
+ specialComesNext = true;
+ }
+ // Not passing this test means removing a '\'.
+ if (!specialComesNext || n === '\\') {
+ out.push(c);
+ }
+ } else {
+ out.push(c);
+ if (specialComesNext && n !== '\\') {
+ out.push('\\');
+ }
+ }
+ }
+ }
+ return out.join('');
+ }
+
+ // Translates the replace part of a search and replace from ex (vim) syntax into
+ // javascript form. Similar to translateRegex, but additionally fixes back references
+ // (translates '\[0..9]' to '$[0..9]') and follows different rules for escaping '$'.
+ var charUnescapes = {'\\n': '\n', '\\r': '\r', '\\t': '\t'};
+ function translateRegexReplace(str) {
+ var escapeNextChar = false;
+ var out = [];
+ for (var i = -1; i < str.length; i++) {
+ var c = str.charAt(i) || '';
+ var n = str.charAt(i+1) || '';
+ if (charUnescapes[c + n]) {
+ out.push(charUnescapes[c+n]);
+ i++;
+ } else if (escapeNextChar) {
+ // At any point in the loop, escapeNextChar is true if the previous
+ // character was a '\' and was not escaped.
+ out.push(c);
+ escapeNextChar = false;
+ } else {
+ if (c === '\\') {
+ escapeNextChar = true;
+ if ((isNumber(n) || n === '$')) {
+ out.push('$');
+ } else if (n !== '/' && n !== '\\') {
+ out.push('\\');
+ }
+ } else {
+ if (c === '$') {
+ out.push('$');
+ }
+ out.push(c);
+ if (n === '/') {
+ out.push('\\');
+ }
+ }
+ }
+ }
+ return out.join('');
+ }
+
+ // Unescape \ and / in the replace part, for PCRE mode.
+ var unescapes = {'\\/': '/', '\\\\': '\\', '\\n': '\n', '\\r': '\r', '\\t': '\t', '\\&':'&'};
+ function unescapeRegexReplace(str) {
+ var stream = new CodeMirror.StringStream(str);
+ var output = [];
+ while (!stream.eol()) {
+ // Search for \.
+ while (stream.peek() && stream.peek() != '\\') {
+ output.push(stream.next());
+ }
+ var matched = false;
+ for (var matcher in unescapes) {
+ if (stream.match(matcher, true)) {
+ matched = true;
+ output.push(unescapes[matcher]);
+ break;
+ }
+ }
+ if (!matched) {
+ // Don't change anything
+ output.push(stream.next());
+ }
+ }
+ return output.join('');
+ }
+
+ /**
+ * Extract the regular expression from the query and return a Regexp object.
+ * Returns null if the query is blank.
+ * If ignoreCase is passed in, the Regexp object will have the 'i' flag set.
+ * If smartCase is passed in, and the query contains upper case letters,
+ * then ignoreCase is overridden, and the 'i' flag will not be set.
+ * If the query contains the /i in the flag part of the regular expression,
+ * then both ignoreCase and smartCase are ignored, and 'i' will be passed
+ * through to the Regex object.
+ */
+ function parseQuery(query, ignoreCase, smartCase) {
+ // First update the last search register
+ var lastSearchRegister = vimGlobalState.registerController.getRegister('/');
+ lastSearchRegister.setText(query);
+ // Check if the query is already a regex.
+ if (query instanceof RegExp) { return query; }
+ // First try to extract regex + flags from the input. If no flags found,
+ // extract just the regex. IE does not accept flags directly defined in
+ // the regex string in the form /regex/flags
+ var slashes = findUnescapedSlashes(query);
+ var regexPart;
+ var forceIgnoreCase;
+ if (!slashes.length) {
+ // Query looks like 'regexp'
+ regexPart = query;
+ } else {
+ // Query looks like 'regexp/...'
+ regexPart = query.substring(0, slashes[0]);
+ var flagsPart = query.substring(slashes[0]);
+ forceIgnoreCase = (flagsPart.indexOf('i') != -1);
+ }
+ if (!regexPart) {
+ return null;
+ }
+ if (!getOption('pcre')) {
+ regexPart = translateRegex(regexPart);
+ }
+ if (smartCase) {
+ ignoreCase = (/^[^A-Z]*$/).test(regexPart);
+ }
+ var regexp = new RegExp(regexPart,
+ (ignoreCase || forceIgnoreCase) ? 'i' : undefined);
+ return regexp;
+ }
+ function showConfirm(cm, text) {
+ if (cm.openNotification) {
+ cm.openNotification('<span style="color: red">' + text + '</span>',
+ {bottom: true, duration: 5000});
+ } else {
+ alert(text);
+ }
+ }
+ function makePrompt(prefix, desc) {
+ var raw = '<span style="font-family: monospace; white-space: pre">' +
+ (prefix || "") + '<input type="text"></span>';
+ if (desc)
+ raw += ' <span style="color: #888">' + desc + '</span>';
+ return raw;
+ }
+ var searchPromptDesc = '(Javascript regexp)';
+ function showPrompt(cm, options) {
+ var shortText = (options.prefix || '') + ' ' + (options.desc || '');
+ var prompt = makePrompt(options.prefix, options.desc);
+ dialog(cm, prompt, shortText, options.onClose, options);
+ }
+ function regexEqual(r1, r2) {
+ if (r1 instanceof RegExp && r2 instanceof RegExp) {
+ var props = ['global', 'multiline', 'ignoreCase', 'source'];
+ for (var i = 0; i < props.length; i++) {
+ var prop = props[i];
+ if (r1[prop] !== r2[prop]) {
+ return false;
+ }
+ }
+ return true;
+ }
+ return false;
+ }
+ // Returns true if the query is valid.
+ function updateSearchQuery(cm, rawQuery, ignoreCase, smartCase) {
+ if (!rawQuery) {
+ return;
+ }
+ var state = getSearchState(cm);
+ var query = parseQuery(rawQuery, !!ignoreCase, !!smartCase);
+ if (!query) {
+ return;
+ }
+ highlightSearchMatches(cm, query);
+ if (regexEqual(query, state.getQuery())) {
+ return query;
+ }
+ state.setQuery(query);
+ return query;
+ }
+ function searchOverlay(query) {
+ if (query.source.charAt(0) == '^') {
+ var matchSol = true;
+ }
+ return {
+ token: function(stream) {
+ if (matchSol && !stream.sol()) {
+ stream.skipToEnd();
+ return;
+ }
+ var match = stream.match(query, false);
+ if (match) {
+ if (match[0].length == 0) {
+ // Matched empty string, skip to next.
+ stream.next();
+ return 'searching';
+ }
+ if (!stream.sol()) {
+ // Backtrack 1 to match \b
+ stream.backUp(1);
+ if (!query.exec(stream.next() + match[0])) {
+ stream.next();
+ return null;
+ }
+ }
+ stream.match(query);
+ return 'searching';
+ }
+ while (!stream.eol()) {
+ stream.next();
+ if (stream.match(query, false)) break;
+ }
+ },
+ query: query
+ };
+ }
+ var highlightTimeout = 0;
+ function highlightSearchMatches(cm, query) {
+ clearTimeout(highlightTimeout);
+ highlightTimeout = setTimeout(function() {
+ var searchState = getSearchState(cm);
+ var overlay = searchState.getOverlay();
+ if (!overlay || query != overlay.query) {
+ if (overlay) {
+ cm.removeOverlay(overlay);
+ }
+ overlay = searchOverlay(query);
+ cm.addOverlay(overlay);
+ if (cm.showMatchesOnScrollbar) {
+ if (searchState.getScrollbarAnnotate()) {
+ searchState.getScrollbarAnnotate().clear();
+ }
+ searchState.setScrollbarAnnotate(cm.showMatchesOnScrollbar(query));
+ }
+ searchState.setOverlay(overlay);
+ }
+ }, 50);
+ }
+ function findNext(cm, prev, query, repeat) {
+ if (repeat === undefined) { repeat = 1; }
+ return cm.operation(function() {
+ var pos = cm.getCursor();
+ var cursor = cm.getSearchCursor(query, pos);
+ for (var i = 0; i < repeat; i++) {
+ var found = cursor.find(prev);
+ if (i == 0 && found && cursorEqual(cursor.from(), pos)) { found = cursor.find(prev); }
+ if (!found) {
+ // SearchCursor may have returned null because it hit EOF, wrap
+ // around and try again.
+ cursor = cm.getSearchCursor(query,
+ (prev) ? Pos(cm.lastLine()) : Pos(cm.firstLine(), 0) );
+ if (!cursor.find(prev)) {
+ return;
+ }
+ }
+ }
+ return cursor.from();
+ });
+ }
+ function clearSearchHighlight(cm) {
+ var state = getSearchState(cm);
+ cm.removeOverlay(getSearchState(cm).getOverlay());
+ state.setOverlay(null);
+ if (state.getScrollbarAnnotate()) {
+ state.getScrollbarAnnotate().clear();
+ state.setScrollbarAnnotate(null);
+ }
+ }
+ /**
+ * Check if pos is in the specified range, INCLUSIVE.
+ * Range can be specified with 1 or 2 arguments.
+ * If the first range argument is an array, treat it as an array of line
+ * numbers. Match pos against any of the lines.
+ * If the first range argument is a number,
+ * if there is only 1 range argument, check if pos has the same line
+ * number
+ * if there are 2 range arguments, then check if pos is in between the two
+ * range arguments.
+ */
+ function isInRange(pos, start, end) {
+ if (typeof pos != 'number') {
+ // Assume it is a cursor position. Get the line number.
+ pos = pos.line;
+ }
+ if (start instanceof Array) {
+ return inArray(pos, start);
+ } else {
+ if (end) {
+ return (pos >= start && pos <= end);
+ } else {
+ return pos == start;
+ }
+ }
+ }
+ function getUserVisibleLines(cm) {
+ var scrollInfo = cm.getScrollInfo();
+ var occludeToleranceTop = 6;
+ var occludeToleranceBottom = 10;
+ var from = cm.coordsChar({left:0, top: occludeToleranceTop + scrollInfo.top}, 'local');
+ var bottomY = scrollInfo.clientHeight - occludeToleranceBottom + scrollInfo.top;
+ var to = cm.coordsChar({left:0, top: bottomY}, 'local');
+ return {top: from.line, bottom: to.line};
+ }
+
+ function getMarkPos(cm, vim, markName) {
+ if (markName == '\'') {
+ var history = cm.doc.history.done;
+ var event = history[history.length - 2];
+ return event && event.ranges && event.ranges[0].head;
+ } else if (markName == '.') {
+ if (cm.doc.history.lastModTime == 0) {
+ return // If no changes, bail out; don't bother to copy or reverse history array.
+ } else {
+ var changeHistory = cm.doc.history.done.filter(function(el){ if (el.changes !== undefined) { return el } });
+ changeHistory.reverse();
+ var lastEditPos = changeHistory[0].changes[0].to;
+ }
+ return lastEditPos;
+ }
+
+ var mark = vim.marks[markName];
+ return mark && mark.find();
+ }
+
+ var ExCommandDispatcher = function() {
+ this.buildCommandMap_();
+ };
+ ExCommandDispatcher.prototype = {
+ processCommand: function(cm, input, opt_params) {
+ var that = this;
+ cm.operation(function () {
+ cm.curOp.isVimOp = true;
+ that._processCommand(cm, input, opt_params);
+ });
+ },
+ _processCommand: function(cm, input, opt_params) {
+ var vim = cm.state.vim;
+ var commandHistoryRegister = vimGlobalState.registerController.getRegister(':');
+ var previousCommand = commandHistoryRegister.toString();
+ if (vim.visualMode) {
+ exitVisualMode(cm);
+ }
+ var inputStream = new CodeMirror.StringStream(input);
+ // update ": with the latest command whether valid or invalid
+ commandHistoryRegister.setText(input);
+ var params = opt_params || {};
+ params.input = input;
+ try {
+ this.parseInput_(cm, inputStream, params);
+ } catch(e) {
+ showConfirm(cm, e);
+ throw e;
+ }
+ var command;
+ var commandName;
+ if (!params.commandName) {
+ // If only a line range is defined, move to the line.
+ if (params.line !== undefined) {
+ commandName = 'move';
+ }
+ } else {
+ command = this.matchCommand_(params.commandName);
+ if (command) {
+ commandName = command.name;
+ if (command.excludeFromCommandHistory) {
+ commandHistoryRegister.setText(previousCommand);
+ }
+ this.parseCommandArgs_(inputStream, params, command);
+ if (command.type == 'exToKey') {
+ // Handle Ex to Key mapping.
+ for (var i = 0; i < command.toKeys.length; i++) {
+ CodeMirror.Vim.handleKey(cm, command.toKeys[i], 'mapping');
+ }
+ return;
+ } else if (command.type == 'exToEx') {
+ // Handle Ex to Ex mapping.
+ this.processCommand(cm, command.toInput);
+ return;
+ }
+ }
+ }
+ if (!commandName) {
+ showConfirm(cm, 'Not an editor command ":' + input + '"');
+ return;
+ }
+ try {
+ exCommands[commandName](cm, params);
+ // Possibly asynchronous commands (e.g. substitute, which might have a
+ // user confirmation), are responsible for calling the callback when
+ // done. All others have it taken care of for them here.
+ if ((!command || !command.possiblyAsync) && params.callback) {
+ params.callback();
+ }
+ } catch(e) {
+ showConfirm(cm, e);
+ throw e;
+ }
+ },
+ parseInput_: function(cm, inputStream, result) {
+ inputStream.eatWhile(':');
+ // Parse range.
+ if (inputStream.eat('%')) {
+ result.line = cm.firstLine();
+ result.lineEnd = cm.lastLine();
+ } else {
+ result.line = this.parseLineSpec_(cm, inputStream);
+ if (result.line !== undefined && inputStream.eat(',')) {
+ result.lineEnd = this.parseLineSpec_(cm, inputStream);
+ }
+ }
+
+ // Parse command name.
+ var commandMatch = inputStream.match(/^(\w+)/);
+ if (commandMatch) {
+ result.commandName = commandMatch[1];
+ } else {
+ result.commandName = inputStream.match(/.*/)[0];
+ }
+
+ return result;
+ },
+ parseLineSpec_: function(cm, inputStream) {
+ var numberMatch = inputStream.match(/^(\d+)/);
+ if (numberMatch) {
+ // Absolute line number plus offset (N+M or N-M) is probably a typo,
+ // not something the user actually wanted. (NB: vim does allow this.)
+ return parseInt(numberMatch[1], 10) - 1;
+ }
+ switch (inputStream.next()) {
+ case '.':
+ return this.parseLineSpecOffset_(inputStream, cm.getCursor().line);
+ case '$':
+ return this.parseLineSpecOffset_(inputStream, cm.lastLine());
+ case '\'':
+ var markName = inputStream.next();
+ var markPos = getMarkPos(cm, cm.state.vim, markName);
+ if (!markPos) throw new Error('Mark not set');
+ return this.parseLineSpecOffset_(inputStream, markPos.line);
+ case '-':
+ case '+':
+ inputStream.backUp(1);
+ // Offset is relative to current line if not otherwise specified.
+ return this.parseLineSpecOffset_(inputStream, cm.getCursor().line);
+ default:
+ inputStream.backUp(1);
+ return undefined;
+ }
+ },
+ parseLineSpecOffset_: function(inputStream, line) {
+ var offsetMatch = inputStream.match(/^([+-])?(\d+)/);
+ if (offsetMatch) {
+ var offset = parseInt(offsetMatch[2], 10);
+ if (offsetMatch[1] == "-") {
+ line -= offset;
+ } else {
+ line += offset;
+ }
+ }
+ return line;
+ },
+ parseCommandArgs_: function(inputStream, params, command) {
+ if (inputStream.eol()) {
+ return;
+ }
+ params.argString = inputStream.match(/.*/)[0];
+ // Parse command-line arguments
+ var delim = command.argDelimiter || /\s+/;
+ var args = trim(params.argString).split(delim);
+ if (args.length && args[0]) {
+ params.args = args;
+ }
+ },
+ matchCommand_: function(commandName) {
+ // Return the command in the command map that matches the shortest
+ // prefix of the passed in command name. The match is guaranteed to be
+ // unambiguous if the defaultExCommandMap's shortNames are set up
+ // correctly. (see @code{defaultExCommandMap}).
+ for (var i = commandName.length; i > 0; i--) {
+ var prefix = commandName.substring(0, i);
+ if (this.commandMap_[prefix]) {
+ var command = this.commandMap_[prefix];
+ if (command.name.indexOf(commandName) === 0) {
+ return command;
+ }
+ }
+ }
+ return null;
+ },
+ buildCommandMap_: function() {
+ this.commandMap_ = {};
+ for (var i = 0; i < defaultExCommandMap.length; i++) {
+ var command = defaultExCommandMap[i];
+ var key = command.shortName || command.name;
+ this.commandMap_[key] = command;
+ }
+ },
+ map: function(lhs, rhs, ctx) {
+ if (lhs != ':' && lhs.charAt(0) == ':') {
+ if (ctx) { throw Error('Mode not supported for ex mappings'); }
+ var commandName = lhs.substring(1);
+ if (rhs != ':' && rhs.charAt(0) == ':') {
+ // Ex to Ex mapping
+ this.commandMap_[commandName] = {
+ name: commandName,
+ type: 'exToEx',
+ toInput: rhs.substring(1),
+ user: true
+ };
+ } else {
+ // Ex to key mapping
+ this.commandMap_[commandName] = {
+ name: commandName,
+ type: 'exToKey',
+ toKeys: rhs,
+ user: true
+ };
+ }
+ } else {
+ if (rhs != ':' && rhs.charAt(0) == ':') {
+ // Key to Ex mapping.
+ var mapping = {
+ keys: lhs,
+ type: 'keyToEx',
+ exArgs: { input: rhs.substring(1) }
+ };
+ if (ctx) { mapping.context = ctx; }
+ defaultKeymap.unshift(mapping);
+ } else {
+ // Key to key mapping
+ var mapping = {
+ keys: lhs,
+ type: 'keyToKey',
+ toKeys: rhs
+ };
+ if (ctx) { mapping.context = ctx; }
+ defaultKeymap.unshift(mapping);
+ }
+ }
+ },
+ unmap: function(lhs, ctx) {
+ if (lhs != ':' && lhs.charAt(0) == ':') {
+ // Ex to Ex or Ex to key mapping
+ if (ctx) { throw Error('Mode not supported for ex mappings'); }
+ var commandName = lhs.substring(1);
+ if (this.commandMap_[commandName] && this.commandMap_[commandName].user) {
+ delete this.commandMap_[commandName];
+ return;
+ }
+ } else {
+ // Key to Ex or key to key mapping
+ var keys = lhs;
+ for (var i = 0; i < defaultKeymap.length; i++) {
+ if (keys == defaultKeymap[i].keys
+ && defaultKeymap[i].context === ctx) {
+ defaultKeymap.splice(i, 1);
+ return;
+ }
+ }
+ }
+ throw Error('No such mapping.');
+ }
+ };
+
+ var exCommands = {
+ colorscheme: function(cm, params) {
+ if (!params.args || params.args.length < 1) {
+ showConfirm(cm, cm.getOption('theme'));
+ return;
+ }
+ cm.setOption('theme', params.args[0]);
+ },
+ map: function(cm, params, ctx) {
+ var mapArgs = params.args;
+ if (!mapArgs || mapArgs.length < 2) {
+ if (cm) {
+ showConfirm(cm, 'Invalid mapping: ' + params.input);
+ }
+ return;
+ }
+ exCommandDispatcher.map(mapArgs[0], mapArgs[1], ctx);
+ },
+ imap: function(cm, params) { this.map(cm, params, 'insert'); },
+ nmap: function(cm, params) { this.map(cm, params, 'normal'); },
+ vmap: function(cm, params) { this.map(cm, params, 'visual'); },
+ unmap: function(cm, params, ctx) {
+ var mapArgs = params.args;
+ if (!mapArgs || mapArgs.length < 1) {
+ if (cm) {
+ showConfirm(cm, 'No such mapping: ' + params.input);
+ }
+ return;
+ }
+ exCommandDispatcher.unmap(mapArgs[0], ctx);
+ },
+ move: function(cm, params) {
+ commandDispatcher.processCommand(cm, cm.state.vim, {
+ type: 'motion',
+ motion: 'moveToLineOrEdgeOfDocument',
+ motionArgs: { forward: false, explicitRepeat: true,
+ linewise: true },
+ repeatOverride: params.line+1});
+ },
+ set: function(cm, params) {
+ var setArgs = params.args;
+ // Options passed through to the setOption/getOption calls. May be passed in by the
+ // local/global versions of the set command
+ var setCfg = params.setCfg || {};
+ if (!setArgs || setArgs.length < 1) {
+ if (cm) {
+ showConfirm(cm, 'Invalid mapping: ' + params.input);
+ }
+ return;
+ }
+ var expr = setArgs[0].split('=');
+ var optionName = expr[0];
+ var value = expr[1];
+ var forceGet = false;
+
+ if (optionName.charAt(optionName.length - 1) == '?') {
+ // If post-fixed with ?, then the set is actually a get.
+ if (value) { throw Error('Trailing characters: ' + params.argString); }
+ optionName = optionName.substring(0, optionName.length - 1);
+ forceGet = true;
+ }
+ if (value === undefined && optionName.substring(0, 2) == 'no') {
+ // To set boolean options to false, the option name is prefixed with
+ // 'no'.
+ optionName = optionName.substring(2);
+ value = false;
+ }
+
+ var optionIsBoolean = options[optionName] && options[optionName].type == 'boolean';
+ if (optionIsBoolean && value == undefined) {
+ // Calling set with a boolean option sets it to true.
+ value = true;
+ }
+ // If no value is provided, then we assume this is a get.
+ if (!optionIsBoolean && value === undefined || forceGet) {
+ var oldValue = getOption(optionName, cm, setCfg);
+ if (oldValue instanceof Error) {
+ showConfirm(cm, oldValue.message);
+ } else if (oldValue === true || oldValue === false) {
+ showConfirm(cm, ' ' + (oldValue ? '' : 'no') + optionName);
+ } else {
+ showConfirm(cm, ' ' + optionName + '=' + oldValue);
+ }
+ } else {
+ var setOptionReturn = setOption(optionName, value, cm, setCfg);
+ if (setOptionReturn instanceof Error) {
+ showConfirm(cm, setOptionReturn.message);
+ }
+ }
+ },
+ setlocal: function (cm, params) {
+ // setCfg is passed through to setOption
+ params.setCfg = {scope: 'local'};
+ this.set(cm, params);
+ },
+ setglobal: function (cm, params) {
+ // setCfg is passed through to setOption
+ params.setCfg = {scope: 'global'};
+ this.set(cm, params);
+ },
+ registers: function(cm, params) {
+ var regArgs = params.args;
+ var registers = vimGlobalState.registerController.registers;
+ var regInfo = '----------Registers----------<br><br>';
+ if (!regArgs) {
+ for (var registerName in registers) {
+ var text = registers[registerName].toString();
+ if (text.length) {
+ regInfo += '"' + registerName + ' ' + text + '<br>';
+ }
+ }
+ } else {
+ var registerName;
+ regArgs = regArgs.join('');
+ for (var i = 0; i < regArgs.length; i++) {
+ registerName = regArgs.charAt(i);
+ if (!vimGlobalState.registerController.isValidRegister(registerName)) {
+ continue;
+ }
+ var register = registers[registerName] || new Register();
+ regInfo += '"' + registerName + ' ' + register.toString() + '<br>';
+ }
+ }
+ showConfirm(cm, regInfo);
+ },
+ sort: function(cm, params) {
+ var reverse, ignoreCase, unique, number, pattern;
+ function parseArgs() {
+ if (params.argString) {
+ var args = new CodeMirror.StringStream(params.argString);
+ if (args.eat('!')) { reverse = true; }
+ if (args.eol()) { return; }
+ if (!args.eatSpace()) { return 'Invalid arguments'; }
+ var opts = args.match(/([dinuox]+)?\s*(\/.+\/)?\s*/);
+ if (!opts && !args.eol()) { return 'Invalid arguments'; }
+ if (opts[1]) {
+ ignoreCase = opts[1].indexOf('i') != -1;
+ unique = opts[1].indexOf('u') != -1;
+ var decimal = opts[1].indexOf('d') != -1 || opts[1].indexOf('n') != -1 && 1;
+ var hex = opts[1].indexOf('x') != -1 && 1;
+ var octal = opts[1].indexOf('o') != -1 && 1;
+ if (decimal + hex + octal > 1) { return 'Invalid arguments'; }
+ number = decimal && 'decimal' || hex && 'hex' || octal && 'octal';
+ }
+ if (opts[2]) {
+ pattern = new RegExp(opts[2].substr(1, opts[2].length - 2), ignoreCase ? 'i' : '');
+ }
+ }
+ }
+ var err = parseArgs();
+ if (err) {
+ showConfirm(cm, err + ': ' + params.argString);
+ return;
+ }
+ var lineStart = params.line || cm.firstLine();
+ var lineEnd = params.lineEnd || params.line || cm.lastLine();
+ if (lineStart == lineEnd) { return; }
+ var curStart = Pos(lineStart, 0);
+ var curEnd = Pos(lineEnd, lineLength(cm, lineEnd));
+ var text = cm.getRange(curStart, curEnd).split('\n');
+ var numberRegex = pattern ? pattern :
+ (number == 'decimal') ? /(-?)([\d]+)/ :
+ (number == 'hex') ? /(-?)(?:0x)?([0-9a-f]+)/i :
+ (number == 'octal') ? /([0-7]+)/ : null;
+ var radix = (number == 'decimal') ? 10 : (number == 'hex') ? 16 : (number == 'octal') ? 8 : null;
+ var numPart = [], textPart = [];
+ if (number || pattern) {
+ for (var i = 0; i < text.length; i++) {
+ var matchPart = pattern ? text[i].match(pattern) : null;
+ if (matchPart && matchPart[0] != '') {
+ numPart.push(matchPart);
+ } else if (!pattern && numberRegex.exec(text[i])) {
+ numPart.push(text[i]);
+ } else {
+ textPart.push(text[i]);
+ }
+ }
+ } else {
+ textPart = text;
+ }
+ function compareFn(a, b) {
+ if (reverse) { var tmp; tmp = a; a = b; b = tmp; }
+ if (ignoreCase) { a = a.toLowerCase(); b = b.toLowerCase(); }
+ var anum = number && numberRegex.exec(a);
+ var bnum = number && numberRegex.exec(b);
+ if (!anum) { return a < b ? -1 : 1; }
+ anum = parseInt((anum[1] + anum[2]).toLowerCase(), radix);
+ bnum = parseInt((bnum[1] + bnum[2]).toLowerCase(), radix);
+ return anum - bnum;
+ }
+ function comparePatternFn(a, b) {
+ if (reverse) { var tmp; tmp = a; a = b; b = tmp; }
+ if (ignoreCase) { a[0] = a[0].toLowerCase(); b[0] = b[0].toLowerCase(); }
+ return (a[0] < b[0]) ? -1 : 1;
+ }
+ numPart.sort(pattern ? comparePatternFn : compareFn);
+ if (pattern) {
+ for (var i = 0; i < numPart.length; i++) {
+ numPart[i] = numPart[i].input;
+ }
+ } else if (!number) { textPart.sort(compareFn); }
+ text = (!reverse) ? textPart.concat(numPart) : numPart.concat(textPart);
+ if (unique) { // Remove duplicate lines
+ var textOld = text;
+ var lastLine;
+ text = [];
+ for (var i = 0; i < textOld.length; i++) {
+ if (textOld[i] != lastLine) {
+ text.push(textOld[i]);
+ }
+ lastLine = textOld[i];
+ }
+ }
+ cm.replaceRange(text.join('\n'), curStart, curEnd);
+ },
+ global: function(cm, params) {
+ // a global command is of the form
+ // :[range]g/pattern/[cmd]
+ // argString holds the string /pattern/[cmd]
+ var argString = params.argString;
+ if (!argString) {
+ showConfirm(cm, 'Regular Expression missing from global');
+ return;
+ }
+ // range is specified here
+ var lineStart = (params.line !== undefined) ? params.line : cm.firstLine();
+ var lineEnd = params.lineEnd || params.line || cm.lastLine();
+ // get the tokens from argString
+ var tokens = splitBySlash(argString);
+ var regexPart = argString, cmd;
+ if (tokens.length) {
+ regexPart = tokens[0];
+ cmd = tokens.slice(1, tokens.length).join('/');
+ }
+ if (regexPart) {
+ // If regex part is empty, then use the previous query. Otherwise
+ // use the regex part as the new query.
+ try {
+ updateSearchQuery(cm, regexPart, true /** ignoreCase */,
+ true /** smartCase */);
+ } catch (e) {
+ showConfirm(cm, 'Invalid regex: ' + regexPart);
+ return;
+ }
+ }
+ // now that we have the regexPart, search for regex matches in the
+ // specified range of lines
+ var query = getSearchState(cm).getQuery();
+ var matchedLines = [], content = '';
+ for (var i = lineStart; i <= lineEnd; i++) {
+ var matched = query.test(cm.getLine(i));
+ if (matched) {
+ matchedLines.push(i+1);
+ content+= cm.getLine(i) + '<br>';
+ }
+ }
+ // if there is no [cmd], just display the list of matched lines
+ if (!cmd) {
+ showConfirm(cm, content);
+ return;
+ }
+ var index = 0;
+ var nextCommand = function() {
+ if (index < matchedLines.length) {
+ var command = matchedLines[index] + cmd;
+ exCommandDispatcher.processCommand(cm, command, {
+ callback: nextCommand
+ });
+ }
+ index++;
+ };
+ nextCommand();
+ },
+ substitute: function(cm, params) {
+ if (!cm.getSearchCursor) {
+ throw new Error('Search feature not available. Requires searchcursor.js or ' +
+ 'any other getSearchCursor implementation.');
+ }
+ var argString = params.argString;
+ var tokens = argString ? splitBySeparator(argString, argString[0]) : [];
+ var regexPart, replacePart = '', trailing, flagsPart, count;
+ var confirm = false; // Whether to confirm each replace.
+ var global = false; // True to replace all instances on a line, false to replace only 1.
+ if (tokens.length) {
+ regexPart = tokens[0];
+ if (getOption('pcre') && regexPart !== '') {
+ regexPart = new RegExp(regexPart).source; //normalize not escaped characters
+ }
+ replacePart = tokens[1];
+ if (regexPart && regexPart[regexPart.length - 1] === '$') {
+ regexPart = regexPart.slice(0, regexPart.length - 1) + '\\n';
+ replacePart = replacePart ? replacePart + '\n' : '\n';
+ }
+ if (replacePart !== undefined) {
+ if (getOption('pcre')) {
+ replacePart = unescapeRegexReplace(replacePart.replace(/([^\\])&/g,"$1$$&"));
+ } else {
+ replacePart = translateRegexReplace(replacePart);
+ }
+ vimGlobalState.lastSubstituteReplacePart = replacePart;
+ }
+ trailing = tokens[2] ? tokens[2].split(' ') : [];
+ } else {
+ // either the argString is empty or its of the form ' hello/world'
+ // actually splitBySlash returns a list of tokens
+ // only if the string starts with a '/'
+ if (argString && argString.length) {
+ showConfirm(cm, 'Substitutions should be of the form ' +
+ ':s/pattern/replace/');
+ return;
+ }
+ }
+ // After the 3rd slash, we can have flags followed by a space followed
+ // by count.
+ if (trailing) {
+ flagsPart = trailing[0];
+ count = parseInt(trailing[1]);
+ if (flagsPart) {
+ if (flagsPart.indexOf('c') != -1) {
+ confirm = true;
+ flagsPart.replace('c', '');
+ }
+ if (flagsPart.indexOf('g') != -1) {
+ global = true;
+ flagsPart.replace('g', '');
+ }
+ if (getOption('pcre')) {
+ regexPart = regexPart + '/' + flagsPart;
+ } else {
+ regexPart = regexPart.replace(/\//g, "\\/") + '/' + flagsPart;
+ }
+ }
+ }
+ if (regexPart) {
+ // If regex part is empty, then use the previous query. Otherwise use
+ // the regex part as the new query.
+ try {
+ updateSearchQuery(cm, regexPart, true /** ignoreCase */,
+ true /** smartCase */);
+ } catch (e) {
+ showConfirm(cm, 'Invalid regex: ' + regexPart);
+ return;
+ }
+ }
+ replacePart = replacePart || vimGlobalState.lastSubstituteReplacePart;
+ if (replacePart === undefined) {
+ showConfirm(cm, 'No previous substitute regular expression');
+ return;
+ }
+ var state = getSearchState(cm);
+ var query = state.getQuery();
+ var lineStart = (params.line !== undefined) ? params.line : cm.getCursor().line;
+ var lineEnd = params.lineEnd || lineStart;
+ if (lineStart == cm.firstLine() && lineEnd == cm.lastLine()) {
+ lineEnd = Infinity;
+ }
+ if (count) {
+ lineStart = lineEnd;
+ lineEnd = lineStart + count - 1;
+ }
+ var startPos = clipCursorToContent(cm, Pos(lineStart, 0));
+ var cursor = cm.getSearchCursor(query, startPos);
+ doReplace(cm, confirm, global, lineStart, lineEnd, cursor, query, replacePart, params.callback);
+ },
+ redo: CodeMirror.commands.redo,
+ undo: CodeMirror.commands.undo,
+ write: function(cm) {
+ if (CodeMirror.commands.save) {
+ // If a save command is defined, call it.
+ CodeMirror.commands.save(cm);
+ } else if (cm.save) {
+ // Saves to text area if no save command is defined and cm.save() is available.
+ cm.save();
+ }
+ },
+ nohlsearch: function(cm) {
+ clearSearchHighlight(cm);
+ },
+ yank: function (cm) {
+ var cur = copyCursor(cm.getCursor());
+ var line = cur.line;
+ var lineText = cm.getLine(line);
+ vimGlobalState.registerController.pushText(
+ '0', 'yank', lineText, true, true);
+ },
+ delmarks: function(cm, params) {
+ if (!params.argString || !trim(params.argString)) {
+ showConfirm(cm, 'Argument required');
+ return;
+ }
+
+ var state = cm.state.vim;
+ var stream = new CodeMirror.StringStream(trim(params.argString));
+ while (!stream.eol()) {
+ stream.eatSpace();
+
+ // Record the streams position at the beginning of the loop for use
+ // in error messages.
+ var count = stream.pos;
+
+ if (!stream.match(/[a-zA-Z]/, false)) {
+ showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
+ return;
+ }
+
+ var sym = stream.next();
+ // Check if this symbol is part of a range
+ if (stream.match('-', true)) {
+ // This symbol is part of a range.
+
+ // The range must terminate at an alphabetic character.
+ if (!stream.match(/[a-zA-Z]/, false)) {
+ showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
+ return;
+ }
+
+ var startMark = sym;
+ var finishMark = stream.next();
+ // The range must terminate at an alphabetic character which
+ // shares the same case as the start of the range.
+ if (isLowerCase(startMark) && isLowerCase(finishMark) ||
+ isUpperCase(startMark) && isUpperCase(finishMark)) {
+ var start = startMark.charCodeAt(0);
+ var finish = finishMark.charCodeAt(0);
+ if (start >= finish) {
+ showConfirm(cm, 'Invalid argument: ' + params.argString.substring(count));
+ return;
+ }
+
+ // Because marks are always ASCII values, and we have
+ // determined that they are the same case, we can use
+ // their char codes to iterate through the defined range.
+ for (var j = 0; j <= finish - start; j++) {
+ var mark = String.fromCharCode(start + j);
+ delete state.marks[mark];
+ }
+ } else {
+ showConfirm(cm, 'Invalid argument: ' + startMark + '-');
+ return;
+ }
+ } else {
+ // This symbol is a valid mark, and is not part of a range.
+ delete state.marks[sym];
+ }
+ }
+ }
+ };
+
+ var exCommandDispatcher = new ExCommandDispatcher();
+
+ /**
+ * @param {CodeMirror} cm CodeMirror instance we are in.
+ * @param {boolean} confirm Whether to confirm each replace.
+ * @param {Cursor} lineStart Line to start replacing from.
+ * @param {Cursor} lineEnd Line to stop replacing at.
+ * @param {RegExp} query Query for performing matches with.
+ * @param {string} replaceWith Text to replace matches with. May contain $1,
+ * $2, etc for replacing captured groups using Javascript replace.
+ * @param {function()} callback A callback for when the replace is done.
+ */
+ function doReplace(cm, confirm, global, lineStart, lineEnd, searchCursor, query,
+ replaceWith, callback) {
+ // Set up all the functions.
+ cm.state.vim.exMode = true;
+ var done = false;
+ var lastPos = searchCursor.from();
+ function replaceAll() {
+ cm.operation(function() {
+ while (!done) {
+ replace();
+ next();
+ }
+ stop();
+ });
+ }
+ function replace() {
+ var text = cm.getRange(searchCursor.from(), searchCursor.to());
+ var newText = text.replace(query, replaceWith);
+ searchCursor.replace(newText);
+ }
+ function next() {
+ // The below only loops to skip over multiple occurrences on the same
+ // line when 'global' is not true.
+ while(searchCursor.findNext() &&
+ isInRange(searchCursor.from(), lineStart, lineEnd)) {
+ if (!global && lastPos && searchCursor.from().line == lastPos.line) {
+ continue;
+ }
+ cm.scrollIntoView(searchCursor.from(), 30);
+ cm.setSelection(searchCursor.from(), searchCursor.to());
+ lastPos = searchCursor.from();
+ done = false;
+ return;
+ }
+ done = true;
+ }
+ function stop(close) {
+ if (close) { close(); }
+ cm.focus();
+ if (lastPos) {
+ cm.setCursor(lastPos);
+ var vim = cm.state.vim;
+ vim.exMode = false;
+ vim.lastHPos = vim.lastHSPos = lastPos.ch;
+ }
+ if (callback) { callback(); }
+ }
+ function onPromptKeyDown(e, _value, close) {
+ // Swallow all keys.
+ CodeMirror.e_stop(e);
+ var keyName = CodeMirror.keyName(e);
+ switch (keyName) {
+ case 'Y':
+ replace(); next(); break;
+ case 'N':
+ next(); break;
+ case 'A':
+ // replaceAll contains a call to close of its own. We don't want it
+ // to fire too early or multiple times.
+ var savedCallback = callback;
+ callback = undefined;
+ cm.operation(replaceAll);
+ callback = savedCallback;
+ break;
+ case 'L':
+ replace();
+ // fall through and exit.
+ case 'Q':
+ case 'Esc':
+ case 'Ctrl-C':
+ case 'Ctrl-[':
+ stop(close);
+ break;
+ }
+ if (done) { stop(close); }
+ return true;
+ }
+
+ // Actually do replace.
+ next();
+ if (done) {
+ showConfirm(cm, 'No matches for ' + query.source);
+ return;
+ }
+ if (!confirm) {
+ replaceAll();
+ if (callback) { callback(); }
+ return;
+ }
+ showPrompt(cm, {
+ prefix: 'replace with <strong>' + replaceWith + '</strong> (y/n/a/q/l)',
+ onKeyDown: onPromptKeyDown
+ });
+ }
+
+ CodeMirror.keyMap.vim = {
+ attach: attachVimMap,
+ detach: detachVimMap,
+ call: cmKey
+ };
+
+ function exitInsertMode(cm) {
+ var vim = cm.state.vim;
+ var macroModeState = vimGlobalState.macroModeState;
+ var insertModeChangeRegister = vimGlobalState.registerController.getRegister('.');
+ var isPlaying = macroModeState.isPlaying;
+ var lastChange = macroModeState.lastInsertModeChanges;
+ if (!isPlaying) {
+ cm.off('change', onChange);
+ CodeMirror.off(cm.getInputField(), 'keydown', onKeyEventTargetKeyDown);
+ }
+ if (!isPlaying && vim.insertModeRepeat > 1) {
+ // Perform insert mode repeat for commands like 3,a and 3,o.
+ repeatLastEdit(cm, vim, vim.insertModeRepeat - 1,
+ true /** repeatForInsert */);
+ vim.lastEditInputState.repeatOverride = vim.insertModeRepeat;
+ }
+ delete vim.insertModeRepeat;
+ vim.insertMode = false;
+ cm.setCursor(cm.getCursor().line, cm.getCursor().ch-1);
+ cm.setOption('keyMap', 'vim');
+ cm.setOption('disableInput', true);
+ cm.toggleOverwrite(false); // exit replace mode if we were in it.
+ // update the ". register before exiting insert mode
+ insertModeChangeRegister.setText(lastChange.changes.join(''));
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "normal"});
+ if (macroModeState.isRecording) {
+ logInsertModeChange(macroModeState);
+ }
+ }
+
+ function _mapCommand(command) {
+ defaultKeymap.unshift(command);
+ }
+
+ function mapCommand(keys, type, name, args, extra) {
+ var command = {keys: keys, type: type};
+ command[type] = name;
+ command[type + "Args"] = args;
+ for (var key in extra)
+ command[key] = extra[key];
+ _mapCommand(command);
+ }
+
+ // The timeout in milliseconds for the two-character ESC keymap should be
+ // adjusted according to your typing speed to prevent false positives.
+ defineOption('insertModeEscKeysTimeout', 200, 'number');
+
+ CodeMirror.keyMap['vim-insert'] = {
+ // TODO: override navigation keys so that Esc will cancel automatic
+ // indentation from o, O, i_<CR>
+ fallthrough: ['default'],
+ attach: attachVimMap,
+ detach: detachVimMap,
+ call: cmKey
+ };
+
+ CodeMirror.keyMap['vim-replace'] = {
+ 'Backspace': 'goCharLeft',
+ fallthrough: ['vim-insert'],
+ attach: attachVimMap,
+ detach: detachVimMap,
+ call: cmKey
+ };
+
+ function executeMacroRegister(cm, vim, macroModeState, registerName) {
+ var register = vimGlobalState.registerController.getRegister(registerName);
+ if (registerName == ':') {
+ // Read-only register containing last Ex command.
+ if (register.keyBuffer[0]) {
+ exCommandDispatcher.processCommand(cm, register.keyBuffer[0]);
+ }
+ macroModeState.isPlaying = false;
+ return;
+ }
+ var keyBuffer = register.keyBuffer;
+ var imc = 0;
+ macroModeState.isPlaying = true;
+ macroModeState.replaySearchQueries = register.searchQueries.slice(0);
+ for (var i = 0; i < keyBuffer.length; i++) {
+ var text = keyBuffer[i];
+ var match, key;
+ while (text) {
+ // Pull off one command key, which is either a single character
+ // or a special sequence wrapped in '<' and '>', e.g. '<Space>'.
+ match = (/<\w+-.+?>|<\w+>|./).exec(text);
+ key = match[0];
+ text = text.substring(match.index + key.length);
+ CodeMirror.Vim.handleKey(cm, key, 'macro');
+ if (vim.insertMode) {
+ var changes = register.insertModeChanges[imc++].changes;
+ vimGlobalState.macroModeState.lastInsertModeChanges.changes =
+ changes;
+ repeatInsertModeChanges(cm, changes, 1);
+ exitInsertMode(cm);
+ }
+ }
+ }
+ macroModeState.isPlaying = false;
+ }
+
+ function logKey(macroModeState, key) {
+ if (macroModeState.isPlaying) { return; }
+ var registerName = macroModeState.latestRegister;
+ var register = vimGlobalState.registerController.getRegister(registerName);
+ if (register) {
+ register.pushText(key);
+ }
+ }
+
+ function logInsertModeChange(macroModeState) {
+ if (macroModeState.isPlaying) { return; }
+ var registerName = macroModeState.latestRegister;
+ var register = vimGlobalState.registerController.getRegister(registerName);
+ if (register && register.pushInsertModeChanges) {
+ register.pushInsertModeChanges(macroModeState.lastInsertModeChanges);
+ }
+ }
+
+ function logSearchQuery(macroModeState, query) {
+ if (macroModeState.isPlaying) { return; }
+ var registerName = macroModeState.latestRegister;
+ var register = vimGlobalState.registerController.getRegister(registerName);
+ if (register && register.pushSearchQuery) {
+ register.pushSearchQuery(query);
+ }
+ }
+
+ /**
+ * Listens for changes made in insert mode.
+ * Should only be active in insert mode.
+ */
+ function onChange(cm, changeObj) {
+ var macroModeState = vimGlobalState.macroModeState;
+ var lastChange = macroModeState.lastInsertModeChanges;
+ if (!macroModeState.isPlaying) {
+ while(changeObj) {
+ lastChange.expectCursorActivityForChange = true;
+ if (lastChange.ignoreCount > 1) {
+ lastChange.ignoreCount--;
+ } else if (changeObj.origin == '+input' || changeObj.origin == 'paste'
+ || changeObj.origin === undefined /* only in testing */) {
+ var selectionCount = cm.listSelections().length;
+ if (selectionCount > 1)
+ lastChange.ignoreCount = selectionCount;
+ var text = changeObj.text.join('\n');
+ if (lastChange.maybeReset) {
+ lastChange.changes = [];
+ lastChange.maybeReset = false;
+ }
+ if (text) {
+ if (cm.state.overwrite && !/\n/.test(text)) {
+ lastChange.changes.push([text]);
+ } else {
+ lastChange.changes.push(text);
+ }
+ }
+ }
+ // Change objects may be chained with next.
+ changeObj = changeObj.next;
+ }
+ }
+ }
+
+ /**
+ * Listens for any kind of cursor activity on CodeMirror.
+ */
+ function onCursorActivity(cm) {
+ var vim = cm.state.vim;
+ if (vim.insertMode) {
+ // Tracking cursor activity in insert mode (for macro support).
+ var macroModeState = vimGlobalState.macroModeState;
+ if (macroModeState.isPlaying) { return; }
+ var lastChange = macroModeState.lastInsertModeChanges;
+ if (lastChange.expectCursorActivityForChange) {
+ lastChange.expectCursorActivityForChange = false;
+ } else {
+ // Cursor moved outside the context of an edit. Reset the change.
+ lastChange.maybeReset = true;
+ }
+ } else if (!cm.curOp.isVimOp) {
+ handleExternalSelection(cm, vim);
+ }
+ if (vim.visualMode) {
+ updateFakeCursor(cm);
+ }
+ }
+ function updateFakeCursor(cm) {
+ var vim = cm.state.vim;
+ var from = clipCursorToContent(cm, copyCursor(vim.sel.head));
+ var to = offsetCursor(from, 0, 1);
+ if (vim.fakeCursor) {
+ vim.fakeCursor.clear();
+ }
+ vim.fakeCursor = cm.markText(from, to, {className: 'cm-animate-fat-cursor'});
+ }
+ function handleExternalSelection(cm, vim) {
+ var anchor = cm.getCursor('anchor');
+ var head = cm.getCursor('head');
+ // Enter or exit visual mode to match mouse selection.
+ if (vim.visualMode && !cm.somethingSelected()) {
+ exitVisualMode(cm, false);
+ } else if (!vim.visualMode && !vim.insertMode && cm.somethingSelected()) {
+ vim.visualMode = true;
+ vim.visualLine = false;
+ CodeMirror.signal(cm, "vim-mode-change", {mode: "visual"});
+ }
+ if (vim.visualMode) {
+ // Bind CodeMirror selection model to vim selection model.
+ // Mouse selections are considered visual characterwise.
+ var headOffset = !cursorIsBefore(head, anchor) ? -1 : 0;
+ var anchorOffset = cursorIsBefore(head, anchor) ? -1 : 0;
+ head = offsetCursor(head, 0, headOffset);
+ anchor = offsetCursor(anchor, 0, anchorOffset);
+ vim.sel = {
+ anchor: anchor,
+ head: head
+ };
+ updateMark(cm, vim, '<', cursorMin(head, anchor));
+ updateMark(cm, vim, '>', cursorMax(head, anchor));
+ } else if (!vim.insertMode) {
+ // Reset lastHPos if selection was modified by something outside of vim mode e.g. by mouse.
+ vim.lastHPos = cm.getCursor().ch;
+ }
+ }
+
+ /** Wrapper for special keys pressed in insert mode */
+ function InsertModeKey(keyName) {
+ this.keyName = keyName;
+ }
+
+ /**
+ * Handles raw key down events from the text area.
+ * - Should only be active in insert mode.
+ * - For recording deletes in insert mode.
+ */
+ function onKeyEventTargetKeyDown(e) {
+ var macroModeState = vimGlobalState.macroModeState;
+ var lastChange = macroModeState.lastInsertModeChanges;
+ var keyName = CodeMirror.keyName(e);
+ if (!keyName) { return; }
+ function onKeyFound() {
+ if (lastChange.maybeReset) {
+ lastChange.changes = [];
+ lastChange.maybeReset = false;
+ }
+ lastChange.changes.push(new InsertModeKey(keyName));
+ return true;
+ }
+ if (keyName.indexOf('Delete') != -1 || keyName.indexOf('Backspace') != -1) {
+ CodeMirror.lookupKey(keyName, 'vim-insert', onKeyFound);
+ }
+ }
+
+ /**
+ * Repeats the last edit, which includes exactly 1 command and at most 1
+ * insert. Operator and motion commands are read from lastEditInputState,
+ * while action commands are read from lastEditActionCommand.
+ *
+ * If repeatForInsert is true, then the function was called by
+ * exitInsertMode to repeat the insert mode changes the user just made. The
+ * corresponding enterInsertMode call was made with a count.
+ */
+ function repeatLastEdit(cm, vim, repeat, repeatForInsert) {
+ var macroModeState = vimGlobalState.macroModeState;
+ macroModeState.isPlaying = true;
+ var isAction = !!vim.lastEditActionCommand;
+ var cachedInputState = vim.inputState;
+ function repeatCommand() {
+ if (isAction) {
+ commandDispatcher.processAction(cm, vim, vim.lastEditActionCommand);
+ } else {
+ commandDispatcher.evalInput(cm, vim);
+ }
+ }
+ function repeatInsert(repeat) {
+ if (macroModeState.lastInsertModeChanges.changes.length > 0) {
+ // For some reason, repeat cw in desktop VIM does not repeat
+ // insert mode changes. Will conform to that behavior.
+ repeat = !vim.lastEditActionCommand ? 1 : repeat;
+ var changeObject = macroModeState.lastInsertModeChanges;
+ repeatInsertModeChanges(cm, changeObject.changes, repeat);
+ }
+ }
+ vim.inputState = vim.lastEditInputState;
+ if (isAction && vim.lastEditActionCommand.interlaceInsertRepeat) {
+ // o and O repeat have to be interlaced with insert repeats so that the
+ // insertions appear on separate lines instead of the last line.
+ for (var i = 0; i < repeat; i++) {
+ repeatCommand();
+ repeatInsert(1);
+ }
+ } else {
+ if (!repeatForInsert) {
+ // Hack to get the cursor to end up at the right place. If I is
+ // repeated in insert mode repeat, cursor will be 1 insert
+ // change set left of where it should be.
+ repeatCommand();
+ }
+ repeatInsert(repeat);
+ }
+ vim.inputState = cachedInputState;
+ if (vim.insertMode && !repeatForInsert) {
+ // Don't exit insert mode twice. If repeatForInsert is set, then we
+ // were called by an exitInsertMode call lower on the stack.
+ exitInsertMode(cm);
+ }
+ macroModeState.isPlaying = false;
+ }
+
+ function repeatInsertModeChanges(cm, changes, repeat) {
+ function keyHandler(binding) {
+ if (typeof binding == 'string') {
+ CodeMirror.commands[binding](cm);
+ } else {
+ binding(cm);
+ }
+ return true;
+ }
+ var head = cm.getCursor('head');
+ var visualBlock = vimGlobalState.macroModeState.lastInsertModeChanges.visualBlock;
+ if (visualBlock) {
+ // Set up block selection again for repeating the changes.
+ selectForInsert(cm, head, visualBlock + 1);
+ repeat = cm.listSelections().length;
+ cm.setCursor(head);
+ }
+ for (var i = 0; i < repeat; i++) {
+ if (visualBlock) {
+ cm.setCursor(offsetCursor(head, i, 0));
+ }
+ for (var j = 0; j < changes.length; j++) {
+ var change = changes[j];
+ if (change instanceof InsertModeKey) {
+ CodeMirror.lookupKey(change.keyName, 'vim-insert', keyHandler);
+ } else if (typeof change == "string") {
+ var cur = cm.getCursor();
+ cm.replaceRange(change, cur, cur);
+ } else {
+ var start = cm.getCursor();
+ var end = offsetCursor(start, 0, change[0].length);
+ cm.replaceRange(change[0], start, end);
+ }
+ }
+ }
+ if (visualBlock) {
+ cm.setCursor(offsetCursor(head, 0, 1));
+ }
+ }
+
+ resetVimGlobalState();
+ return vimApi;
+ };
+ // Initialize Vim and make it available as an API.
+ CodeMirror.Vim = Vim();
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/lib/codemirror.css b/devtools/client/shared/sourceeditor/codemirror/lib/codemirror.css
new file mode 100644
index 0000000000..a64f97c777
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/lib/codemirror.css
@@ -0,0 +1,350 @@
+/* BASICS */
+
+.CodeMirror {
+ /* Set height, width, borders, and global font properties here */
+ font-family: monospace;
+ height: 300px;
+ color: black;
+ direction: ltr;
+}
+
+/* PADDING */
+
+.CodeMirror-lines {
+ padding: 4px 0; /* Vertical padding around content */
+}
+.CodeMirror pre.CodeMirror-line,
+.CodeMirror pre.CodeMirror-line-like {
+ padding: 0 4px; /* Horizontal padding of content */
+}
+
+.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
+ background-color: white; /* The little square between H and V scrollbars */
+}
+
+/* GUTTER */
+
+.CodeMirror-gutters {
+ border-right: 1px solid #ddd;
+ background-color: #f7f7f7;
+ white-space: nowrap;
+}
+.CodeMirror-linenumbers {}
+.CodeMirror-linenumber {
+ padding: 0 3px 0 5px;
+ min-width: 20px;
+ text-align: right;
+ color: #999;
+ white-space: nowrap;
+}
+
+.CodeMirror-guttermarker { color: black; }
+.CodeMirror-guttermarker-subtle { color: #999; }
+
+/* CURSOR */
+
+.CodeMirror-cursor {
+ border-left: 1px solid black;
+ border-right: none;
+ width: 0;
+}
+/* Shown when moving in bi-directional text */
+.CodeMirror div.CodeMirror-secondarycursor {
+ border-left: 1px solid silver;
+}
+.cm-fat-cursor .CodeMirror-cursor {
+ width: auto;
+ border: 0 !important;
+ background: #7e7;
+}
+.cm-fat-cursor div.CodeMirror-cursors {
+ z-index: 1;
+}
+.cm-fat-cursor-mark {
+ background-color: rgba(20, 255, 20, 0.5);
+ -webkit-animation: blink 1.06s steps(1) infinite;
+ -moz-animation: blink 1.06s steps(1) infinite;
+ animation: blink 1.06s steps(1) infinite;
+}
+.cm-animate-fat-cursor {
+ width: auto;
+ border: 0;
+ -webkit-animation: blink 1.06s steps(1) infinite;
+ -moz-animation: blink 1.06s steps(1) infinite;
+ animation: blink 1.06s steps(1) infinite;
+ background-color: #7e7;
+}
+@-moz-keyframes blink {
+ 0% {}
+ 50% { background-color: transparent; }
+ 100% {}
+}
+@-webkit-keyframes blink {
+ 0% {}
+ 50% { background-color: transparent; }
+ 100% {}
+}
+@keyframes blink {
+ 0% {}
+ 50% { background-color: transparent; }
+ 100% {}
+}
+
+/* Can style cursor different in overwrite (non-insert) mode */
+.CodeMirror-overwrite .CodeMirror-cursor {}
+
+.cm-tab { display: inline-block; text-decoration: inherit; }
+
+.CodeMirror-rulers {
+ position: absolute;
+ left: 0; right: 0; top: -50px; bottom: 0;
+ overflow: hidden;
+}
+.CodeMirror-ruler {
+ border-left: 1px solid #ccc;
+ top: 0; bottom: 0;
+ position: absolute;
+}
+
+/* DEFAULT THEME */
+
+.cm-s-default .cm-header {color: blue;}
+.cm-s-default .cm-quote {color: #090;}
+.cm-negative {color: #d44;}
+.cm-positive {color: #292;}
+.cm-header, .cm-strong {font-weight: bold;}
+.cm-em {font-style: italic;}
+.cm-link {text-decoration: underline;}
+.cm-strikethrough {text-decoration: line-through;}
+
+.cm-s-default .cm-keyword {color: #708;}
+.cm-s-default .cm-atom {color: #219;}
+.cm-s-default .cm-number {color: #164;}
+.cm-s-default .cm-def {color: #00f;}
+.cm-s-default .cm-variable,
+.cm-s-default .cm-punctuation,
+.cm-s-default .cm-property,
+.cm-s-default .cm-operator {}
+.cm-s-default .cm-variable-2 {color: #05a;}
+.cm-s-default .cm-variable-3, .cm-s-default .cm-type {color: #085;}
+.cm-s-default .cm-comment {color: #a50;}
+.cm-s-default .cm-string {color: #a11;}
+.cm-s-default .cm-string-2 {color: #f50;}
+.cm-s-default .cm-meta {color: #555;}
+.cm-s-default .cm-qualifier {color: #555;}
+.cm-s-default .cm-builtin {color: #30a;}
+.cm-s-default .cm-bracket {color: #997;}
+.cm-s-default .cm-tag {color: #170;}
+.cm-s-default .cm-attribute {color: #00c;}
+.cm-s-default .cm-hr {color: #999;}
+.cm-s-default .cm-link {color: #00c;}
+
+.cm-s-default .cm-error {color: #f00;}
+.cm-invalidchar {color: #f00;}
+
+.CodeMirror-composing { border-bottom: 2px solid; }
+
+/* Default styles for common addons */
+
+div.CodeMirror span.CodeMirror-matchingbracket {color: #0b0;}
+div.CodeMirror span.CodeMirror-nonmatchingbracket {color: #a22;}
+.CodeMirror-matchingtag { background: rgba(255, 150, 0, .3); }
+.CodeMirror-activeline-background {background: #e8f2ff;}
+
+/* STOP */
+
+/* The rest of this file contains styles related to the mechanics of
+ the editor. You probably shouldn't touch them. */
+
+.CodeMirror {
+ position: relative;
+ overflow: hidden;
+ background: white;
+}
+
+.CodeMirror-scroll {
+ overflow: scroll !important; /* Things will break if this is overridden */
+ /* 50px is the magic margin used to hide the element's real scrollbars */
+ /* See overflow: hidden in .CodeMirror */
+ margin-bottom: -50px; margin-right: -50px;
+ padding-bottom: 50px;
+ height: 100%;
+ outline: none; /* Prevent dragging from highlighting the element */
+ position: relative;
+}
+.CodeMirror-sizer {
+ position: relative;
+ border-right: 50px solid transparent;
+}
+
+/* The fake, visible scrollbars. Used to force redraw during scrolling
+ before actual scrolling happens, thus preventing shaking and
+ flickering artifacts. */
+.CodeMirror-vscrollbar, .CodeMirror-hscrollbar, .CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
+ position: absolute;
+ z-index: 6;
+ display: none;
+ outline: none;
+}
+.CodeMirror-vscrollbar {
+ right: 0; top: 0;
+ overflow-x: hidden;
+ overflow-y: scroll;
+}
+.CodeMirror-hscrollbar {
+ bottom: 0; left: 0;
+ overflow-y: hidden;
+ overflow-x: scroll;
+}
+.CodeMirror-scrollbar-filler {
+ right: 0; bottom: 0;
+}
+.CodeMirror-gutter-filler {
+ left: 0; bottom: 0;
+}
+
+.CodeMirror-gutters {
+ position: absolute; left: 0; top: 0;
+ min-height: 100%;
+ z-index: 3;
+}
+.CodeMirror-gutter {
+ white-space: normal;
+ height: 100%;
+ display: inline-block;
+ vertical-align: top;
+ margin-bottom: -50px;
+}
+.CodeMirror-gutter-wrapper {
+ position: absolute;
+ z-index: 4;
+ background: none !important;
+ border: none !important;
+}
+.CodeMirror-gutter-background {
+ position: absolute;
+ top: 0; bottom: 0;
+ z-index: 4;
+}
+.CodeMirror-gutter-elt {
+ position: absolute;
+ cursor: default;
+ z-index: 4;
+}
+.CodeMirror-gutter-wrapper ::selection { background-color: transparent }
+.CodeMirror-gutter-wrapper ::-moz-selection { background-color: transparent }
+
+.CodeMirror-lines {
+ cursor: text;
+ min-height: 1px; /* prevents collapsing before first draw */
+}
+.CodeMirror pre.CodeMirror-line,
+.CodeMirror pre.CodeMirror-line-like {
+ /* Reset some styles that the rest of the page might have set */
+ -moz-border-radius: 0; -webkit-border-radius: 0; border-radius: 0;
+ border-width: 0;
+ background: transparent;
+ font-family: inherit;
+ font-size: inherit;
+ margin: 0;
+ white-space: pre;
+ word-wrap: normal;
+ line-height: inherit;
+ color: inherit;
+ z-index: 2;
+ position: relative;
+ overflow: visible;
+ -webkit-tap-highlight-color: transparent;
+ -webkit-font-variant-ligatures: contextual;
+ font-variant-ligatures: contextual;
+}
+.CodeMirror-wrap pre.CodeMirror-line,
+.CodeMirror-wrap pre.CodeMirror-line-like {
+ word-wrap: break-word;
+ white-space: pre-wrap;
+ word-break: normal;
+}
+
+.CodeMirror-linebackground {
+ position: absolute;
+ left: 0; right: 0; top: 0; bottom: 0;
+ z-index: 0;
+}
+
+.CodeMirror-linewidget {
+ position: relative;
+ z-index: 2;
+ padding: 0.1px; /* Force widget margins to stay inside of the container */
+}
+
+.CodeMirror-widget {}
+
+.CodeMirror-rtl pre { direction: rtl; }
+
+.CodeMirror-code {
+ outline: none;
+}
+
+/* Force content-box sizing for the elements where we expect it */
+.CodeMirror-scroll,
+.CodeMirror-sizer,
+.CodeMirror-gutter,
+.CodeMirror-gutters,
+.CodeMirror-linenumber {
+ -moz-box-sizing: content-box;
+ box-sizing: content-box;
+}
+
+.CodeMirror-measure {
+ position: absolute;
+ width: 100%;
+ height: 0;
+ overflow: hidden;
+ visibility: hidden;
+}
+
+.CodeMirror-cursor {
+ position: absolute;
+ pointer-events: none;
+}
+.CodeMirror-measure pre { position: static; }
+
+div.CodeMirror-cursors {
+ visibility: hidden;
+ position: relative;
+ z-index: 3;
+}
+div.CodeMirror-dragcursors {
+ visibility: visible;
+}
+
+.CodeMirror-focused div.CodeMirror-cursors {
+ visibility: visible;
+}
+
+.CodeMirror-selected { background: #d9d9d9; }
+.CodeMirror-focused .CodeMirror-selected { background: #d7d4f0; }
+.CodeMirror-crosshair { cursor: crosshair; }
+.CodeMirror-line::selection, .CodeMirror-line > span::selection, .CodeMirror-line > span > span::selection { background: #d7d4f0; }
+.CodeMirror-line::-moz-selection, .CodeMirror-line > span::-moz-selection, .CodeMirror-line > span > span::-moz-selection { background: #d7d4f0; }
+
+.cm-searching {
+ background-color: #ffa;
+ background-color: rgba(255, 255, 0, .4);
+}
+
+/* Used to force a border model for a node */
+.cm-force-border { padding-right: .1px; }
+
+@media print {
+ /* Hide the cursor when printing */
+ .CodeMirror div.CodeMirror-cursors {
+ visibility: hidden;
+ }
+}
+
+/* See issue #2901 */
+.cm-tab-wrap-hack:after { content: ''; }
+
+/* Help users use markselection to safely style text background */
+span.CodeMirror-selectedtext { background: none; }
diff --git a/devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js b/devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js
new file mode 100644
index 0000000000..88a93243f2
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js
@@ -0,0 +1,9788 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+// This is CodeMirror (https://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 (global, factory) {
+ typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
+ typeof define === 'function' && define.amd ? define(factory) :
+ (global = global || self, global.CodeMirror = factory());
+}(this, (function () { 'use strict';
+
+ // Kludges for bugs and behavior differences that can't be feature
+ // detected are enabled based on userAgent etc sniffing.
+ var userAgent = navigator.userAgent;
+ var platform = navigator.platform;
+
+ var gecko = /gecko\/\d/i.test(userAgent);
+ var ie_upto10 = /MSIE \d/.test(userAgent);
+ var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(userAgent);
+ var edge = /Edge\/(\d+)/.exec(userAgent);
+ var ie = ie_upto10 || ie_11up || edge;
+ var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : +(edge || ie_11up)[1]);
+ var webkit = !edge && /WebKit\//.test(userAgent);
+ var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(userAgent);
+ var chrome = !edge && /Chrome\//.test(userAgent);
+ var presto = /Opera\//.test(userAgent);
+ var safari = /Apple Computer/.test(navigator.vendor);
+ var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(userAgent);
+ var phantom = /PhantomJS/.test(userAgent);
+
+ var ios = !edge && /AppleWebKit/.test(userAgent) && /Mobile\/\w+/.test(userAgent);
+ var android = /Android/.test(userAgent);
+ // This is woefully incomplete. Suggestions for alternative methods welcome.
+ var mobile = ios || android || /webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(userAgent);
+ var mac = ios || /Mac/.test(platform);
+ var chromeOS = /\bCrOS\b/.test(userAgent);
+ var windows = /win/i.test(platform);
+
+ var presto_version = presto && 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_version >= 9);
+
+ function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*") }
+
+ var rmClass = function(node, cls) {
+ var current = node.className;
+ var match = classTest(cls).exec(current);
+ if (match) {
+ var after = current.slice(match.index + match[0].length);
+ node.className = current.slice(0, match.index) + (after ? match[1] + after : "");
+ }
+ };
+
+ 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 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
+ }
+ // wrapper for elt, which removes the elt from the accessibility tree
+ function eltP(tag, content, className, style) {
+ var e = elt(tag, content, className, style);
+ e.setAttribute("role", "presentation");
+ return e
+ }
+
+ var range;
+ if (document.createRange) { range = function(node, start, end, endNode) {
+ var r = document.createRange();
+ r.setEnd(endNode || node, end);
+ r.setStart(node, start);
+ return r
+ }; }
+ else { range = function(node, start, end) {
+ var r = document.body.createTextRange();
+ try { r.moveToElementText(node.parentNode); }
+ catch(e) { return r }
+ r.collapse(true);
+ r.moveEnd("character", end);
+ r.moveStart("character", start);
+ return r
+ }; }
+
+ function contains(parent, child) {
+ if (child.nodeType == 3) // Android browser always returns false when child is a textnode
+ { child = child.parentNode; }
+ if (parent.contains)
+ { return parent.contains(child) }
+ do {
+ if (child.nodeType == 11) { child = child.host; }
+ if (child == parent) { return true }
+ } while (child = child.parentNode)
+ }
+
+ function activeElt() {
+ // IE and Edge may throw an "Unspecified Error" when accessing document.activeElement.
+ // IE < 10 will throw when accessed while the page is loading or in an iframe.
+ // IE > 9 and Edge will throw when accessed in an iframe if document.body is unavailable.
+ var activeElement;
+ try {
+ activeElement = document.activeElement;
+ } catch(e) {
+ activeElement = document.body || null;
+ }
+ while (activeElement && activeElement.shadowRoot && activeElement.shadowRoot.activeElement)
+ { activeElement = activeElement.shadowRoot.activeElement; }
+ return activeElement
+ }
+
+ function addClass(node, cls) {
+ var current = node.className;
+ if (!classTest(cls).test(current)) { node.className += (current ? " " : "") + cls; }
+ }
+ function joinClasses(a, b) {
+ var as = a.split(" ");
+ for (var i = 0; i < as.length; i++)
+ { if (as[i] && !classTest(as[i]).test(b)) { b += " " + as[i]; } }
+ return b
+ }
+
+ 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 bind(f) {
+ var args = Array.prototype.slice.call(arguments, 1);
+ return function(){return f.apply(null, args)}
+ }
+
+ function copyObj(obj, target, overwrite) {
+ if (!target) { target = {}; }
+ for (var prop in obj)
+ { if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop)))
+ { target[prop] = obj[prop]; } }
+ return target
+ }
+
+ // Counts the column offset in a string, taking tabs into account.
+ // Used mostly to find indentation.
+ function countColumn(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;
+ }
+ }
+
+ var Delayed = function() {
+ this.id = null;
+ this.f = null;
+ this.time = 0;
+ this.handler = bind(this.onTimeout, this);
+ };
+ Delayed.prototype.onTimeout = function (self) {
+ self.id = 0;
+ if (self.time <= +new Date) {
+ self.f();
+ } else {
+ setTimeout(self.handler, self.time - +new Date);
+ }
+ };
+ Delayed.prototype.set = function (ms, f) {
+ this.f = f;
+ var time = +new Date + ms;
+ if (!this.id || time < this.time) {
+ clearTimeout(this.id);
+ this.id = setTimeout(this.handler, ms);
+ this.time = time;
+ }
+ };
+
+ function indexOf(array, elt) {
+ for (var i = 0; i < array.length; ++i)
+ { if (array[i] == elt) { return i } }
+ return -1
+ }
+
+ // Number of pixels added to scroller and sizer to hide scrollbar
+ var scrollerGap = 50;
+
+ // Returned or thrown by various protocols to signal 'I'm not
+ // handling this'.
+ var 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"};
+
+ // 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] }
+
+ function map(array, f) {
+ var out = [];
+ for (var i = 0; i < array.length; i++) { out[i] = f(array[i], i); }
+ return out
+ }
+
+ function insertSorted(array, value, score) {
+ var pos = 0, priority = score(value);
+ while (pos < array.length && score(array[pos]) <= priority) { pos++; }
+ array.splice(pos, 0, value);
+ }
+
+ function nothing() {}
+
+ function createObj(base, props) {
+ var inst;
+ if (Object.create) {
+ inst = Object.create(base);
+ } else {
+ nothing.prototype = base;
+ inst = new nothing();
+ }
+ if (props) { copyObj(props, inst); }
+ return inst
+ }
+
+ var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;
+ function isWordCharBasic(ch) {
+ return /\w/.test(ch) || ch > "\x80" &&
+ (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch))
+ }
+ function isWordChar(ch, helper) {
+ if (!helper) { return isWordCharBasic(ch) }
+ if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) { return true }
+ return helper.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) }
+
+ // Returns a number from the range [`0`; `str.length`] unless `pos` is outside that range.
+ function skipExtendingChars(str, pos, dir) {
+ while ((dir < 0 ? pos > 0 : pos < str.length) && isExtendingChar(str.charAt(pos))) { pos += dir; }
+ return pos
+ }
+
+ // Returns the value from the range [`from`; `to`] that satisfies
+ // `pred` and is closest to `from`. Assumes that at least `to`
+ // satisfies `pred`. Supports `from` being greater than `to`.
+ function findFirst(pred, from, to) {
+ // At any point we are certain `to` satisfies `pred`, don't know
+ // whether `from` does.
+ var dir = from > to ? -1 : 1;
+ for (;;) {
+ if (from == to) { return from }
+ var midF = (from + to) / 2, mid = dir < 0 ? Math.ceil(midF) : Math.floor(midF);
+ if (mid == from) { return pred(mid) ? from : to }
+ if (pred(mid)) { to = mid; }
+ else { from = mid + dir; }
+ }
+ }
+
+ // BIDI HELPERS
+
+ function iterateBidiSections(order, from, to, f) {
+ if (!order) { return f(from, to, "ltr", 0) }
+ 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", i);
+ found = true;
+ }
+ }
+ if (!found) { f(from, to, "ltr"); }
+ }
+
+ var bidiOther = null;
+ function getBidiPartAt(order, ch, sticky) {
+ var found;
+ bidiOther = null;
+ for (var i = 0; i < order.length; ++i) {
+ var cur = order[i];
+ if (cur.from < ch && cur.to > ch) { return i }
+ if (cur.to == ch) {
+ if (cur.from != cur.to && sticky == "before") { found = i; }
+ else { bidiOther = i; }
+ }
+ if (cur.from == ch) {
+ if (cur.from != cur.to && sticky != "before") { found = i; }
+ else { bidiOther = i; }
+ }
+ }
+ return found != null ? found : bidiOther
+ }
+
+ // 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 0x6f9
+ var arabicTypes = "nnnnnnNNr%%r,rNNmmmmmmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmmmnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmnNmmmmmmrrmmNmmmmrr1111111111";
+ function charType(code) {
+ if (code <= 0xf7) { return lowTypes.charAt(code) }
+ else if (0x590 <= code && code <= 0x5f4) { return "R" }
+ else if (0x600 <= code && code <= 0x6f9) { 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]/;
+
+ function BidiSpan(level, from, to) {
+ this.level = level;
+ this.from = from; this.to = to;
+ }
+
+ return function(str, direction) {
+ var outerType = direction == "ltr" ? "L" : "R";
+
+ if (str.length == 0 || direction == "ltr" && !bidiRE.test(str)) { return false }
+ var len = str.length, types = [];
+ for (var i = 0; i < len; ++i)
+ { types.push(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$1 = 0, prev = outerType; i$1 < len; ++i$1) {
+ var type = types[i$1];
+ if (type == "m") { types[i$1] = 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$2 = 0, cur = outerType; i$2 < len; ++i$2) {
+ var type$1 = types[i$2];
+ if (type$1 == "1" && cur == "r") { types[i$2] = "n"; }
+ else if (isStrong.test(type$1)) { cur = type$1; if (type$1 == "r") { types[i$2] = "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$3 = 1, prev$1 = types[0]; i$3 < len - 1; ++i$3) {
+ var type$2 = types[i$3];
+ if (type$2 == "+" && prev$1 == "1" && types[i$3+1] == "1") { types[i$3] = "1"; }
+ else if (type$2 == "," && prev$1 == types[i$3+1] &&
+ (prev$1 == "1" || prev$1 == "n")) { types[i$3] = prev$1; }
+ prev$1 = type$2;
+ }
+
+ // 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$4 = 0; i$4 < len; ++i$4) {
+ var type$3 = types[i$4];
+ if (type$3 == ",") { types[i$4] = "N"; }
+ else if (type$3 == "%") {
+ var end = (void 0);
+ for (end = i$4 + 1; end < len && types[end] == "%"; ++end) {}
+ var replace = (i$4 && types[i$4-1] == "!") || (end < len && types[end] == "1") ? "1" : "N";
+ for (var j = i$4; j < end; ++j) { types[j] = replace; }
+ i$4 = 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$5 = 0, cur$1 = outerType; i$5 < len; ++i$5) {
+ var type$4 = types[i$5];
+ if (cur$1 == "L" && type$4 == "1") { types[i$5] = "L"; }
+ else if (isStrong.test(type$4)) { cur$1 = type$4; }
+ }
+
+ // 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$6 = 0; i$6 < len; ++i$6) {
+ if (isNeutral.test(types[i$6])) {
+ var end$1 = (void 0);
+ for (end$1 = i$6 + 1; end$1 < len && isNeutral.test(types[end$1]); ++end$1) {}
+ var before = (i$6 ? types[i$6-1] : outerType) == "L";
+ var after = (end$1 < len ? types[end$1] : outerType) == "L";
+ var replace$1 = before == after ? (before ? "L" : "R") : outerType;
+ for (var j$1 = i$6; j$1 < end$1; ++j$1) { types[j$1] = replace$1; }
+ i$6 = end$1 - 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$7 = 0; i$7 < len;) {
+ if (countsAsLeft.test(types[i$7])) {
+ var start = i$7;
+ for (++i$7; i$7 < len && countsAsLeft.test(types[i$7]); ++i$7) {}
+ order.push(new BidiSpan(0, start, i$7));
+ } else {
+ var pos = i$7, at = order.length, isRTL = direction == "rtl" ? 1 : 0;
+ for (++i$7; i$7 < len && types[i$7] != "L"; ++i$7) {}
+ for (var j$2 = pos; j$2 < i$7;) {
+ if (countsAsNum.test(types[j$2])) {
+ if (pos < j$2) { order.splice(at, 0, new BidiSpan(1, pos, j$2)); at += isRTL; }
+ var nstart = j$2;
+ for (++j$2; j$2 < i$7 && countsAsNum.test(types[j$2]); ++j$2) {}
+ order.splice(at, 0, new BidiSpan(2, nstart, j$2));
+ at += isRTL;
+ pos = j$2;
+ } else { ++j$2; }
+ }
+ if (pos < i$7) { order.splice(at, 0, new BidiSpan(1, pos, i$7)); }
+ }
+ }
+ if (direction == "ltr") {
+ 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));
+ }
+ }
+
+ return direction == "rtl" ? order.reverse() : order
+ }
+ })();
+
+ // 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, direction) {
+ var order = line.order;
+ if (order == null) { order = line.order = bidiOrdering(line.text, direction); }
+ return order
+ }
+
+ // EVENT HANDLING
+
+ // Lightweight event framework. on/off also work on DOM nodes,
+ // registering native DOM handlers.
+
+ var noHandlers = [];
+
+ var 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 = {});
+ map[type] = (map[type] || noHandlers).concat(f);
+ }
+ };
+
+ function getHandlers(emitter, type) {
+ return emitter._handlers && emitter._handlers[type] || noHandlers
+ }
+
+ function off(emitter, type, f) {
+ if (emitter.removeEventListener) {
+ emitter.removeEventListener(type, f, false);
+ } else if (emitter.detachEvent) {
+ emitter.detachEvent("on" + type, f);
+ } else {
+ var map = emitter._handlers, arr = map && map[type];
+ if (arr) {
+ var index = indexOf(arr, f);
+ if (index > -1)
+ { map[type] = arr.slice(0, index).concat(arr.slice(index + 1)); }
+ }
+ }
+ }
+
+ function signal(emitter, type /*, values...*/) {
+ var handlers = getHandlers(emitter, type);
+ if (!handlers.length) { return }
+ var args = Array.prototype.slice.call(arguments, 2);
+ for (var i = 0; i < handlers.length; ++i) { handlers[i].apply(null, args); }
+ }
+
+ // 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) {
+ if (typeof e == "string")
+ { e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; }
+ signal(cm, override || e.type, cm, e);
+ return e_defaultPrevented(e) || e.codemirrorIgnore
+ }
+
+ function signalCursorActivity(cm) {
+ var arr = cm._handlers && cm._handlers.cursorActivity;
+ if (!arr) { return }
+ var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []);
+ for (var i = 0; i < arr.length; ++i) { if (indexOf(set, arr[i]) == -1)
+ { set.push(arr[i]); } }
+ }
+
+ function hasHandler(emitter, type) {
+ return getHandlers(emitter, type).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);};
+ }
+
+ // Due to the fact that we still support jurassic IE versions, some
+ // compatibility wrappers are needed.
+
+ function e_preventDefault(e) {
+ if (e.preventDefault) { e.preventDefault(); }
+ else { e.returnValue = false; }
+ }
+ function e_stopPropagation(e) {
+ if (e.stopPropagation) { e.stopPropagation(); }
+ else { e.cancelBubble = true; }
+ }
+ function e_defaultPrevented(e) {
+ return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false
+ }
+ function e_stop(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
+ }
+
+ // 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 && ie_version < 9) { return false }
+ var div = elt('div');
+ return "draggable" in div || "dragDrop" in div
+ }();
+
+ 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 && ie_version < 8); }
+ }
+ var node = zwspSupported ? elt("span", "\u200b") :
+ elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px");
+ node.setAttribute("cm-text", "");
+ return node
+ }
+
+ // 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();
+ var r1 = range(txt, 1, 2).getBoundingClientRect();
+ removeChildren(measure);
+ if (!r0 || r0.left == r0.right) { return false } // Safari returns null in some cases (#2780)
+ 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 splitLinesAuto = "\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) {
+ var range;
+ try {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"
+ })();
+
+ var badZoomedRects = null;
+ function hasBadZoomedRects(measure) {
+ if (badZoomedRects != null) { return badZoomedRects }
+ var node = removeChildrenAndAdd(measure, elt("span", "x"));
+ var normal = node.getBoundingClientRect();
+ var fromRange = range(node, 0, 1).getBoundingClientRect();
+ return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1
+ }
+
+ // Known modes, by name and by MIME
+ var modes = {}, 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.)
+ function defineMode(name, mode) {
+ if (arguments.length > 2)
+ { mode.dependencies = Array.prototype.slice.call(arguments, 2); }
+ modes[name] = mode;
+ }
+
+ function defineMIME(mime, spec) {
+ mimeModes[mime] = spec;
+ }
+
+ // Given a MIME type, a {name, ...options} config object, or a name
+ // string, return a mode config object.
+ function resolveMode(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 resolveMode("application/xml")
+ } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+json$/.test(spec)) {
+ return resolveMode("application/json")
+ }
+ 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.
+ function getMode(options, spec) {
+ spec = resolveMode(spec);
+ var mfactory = modes[spec.name];
+ if (!mfactory) { return 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$1 in spec.modeProps)
+ { modeObj[prop$1] = spec.modeProps[prop$1]; } }
+
+ return modeObj
+ }
+
+ // This can be used to attach properties to mode objects from
+ // outside the actual mode definition.
+ var modeExtensions = {};
+ function extendMode(mode, properties) {
+ var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {});
+ copyObj(properties, exts);
+ }
+
+ function copyState(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
+ }
+
+ // Given a mode and a state (for that mode), find the inner mode and
+ // state at the position that the state refers to.
+ function innerMode(mode, state) {
+ var info;
+ while (mode.innerMode) {
+ info = mode.innerMode(state);
+ if (!info || info.mode == mode) { break }
+ state = info.state;
+ mode = info.mode;
+ }
+ return info || {mode: mode, state: state}
+ }
+
+ function startState(mode, a1, a2) {
+ return mode.startState ? mode.startState(a1, a2) : true
+ }
+
+ // STRING STREAM
+
+ // Fed to the mode parsers, provides helper functions to make
+ // parsers more succinct.
+
+ var StringStream = function(string, tabSize, lineOracle) {
+ this.pos = this.start = 0;
+ this.string = string;
+ this.tabSize = tabSize || 8;
+ this.lastColumnPos = this.lastColumnValue = 0;
+ this.lineStart = 0;
+ this.lineOracle = lineOracle;
+ };
+
+ StringStream.prototype.eol = function () {return this.pos >= this.string.length};
+ StringStream.prototype.sol = function () {return this.pos == this.lineStart};
+ StringStream.prototype.peek = function () {return this.string.charAt(this.pos) || undefined};
+ StringStream.prototype.next = function () {
+ if (this.pos < this.string.length)
+ { return this.string.charAt(this.pos++) }
+ };
+ StringStream.prototype.eat = function (match) {
+ var ch = this.string.charAt(this.pos);
+ var ok;
+ if (typeof match == "string") { ok = ch == match; }
+ else { ok = ch && (match.test ? match.test(ch) : match(ch)); }
+ if (ok) {++this.pos; return ch}
+ };
+ StringStream.prototype.eatWhile = function (match) {
+ var start = this.pos;
+ while (this.eat(match)){}
+ return this.pos > start
+ };
+ StringStream.prototype.eatSpace = function () {
+ var start = this.pos;
+ while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) { ++this.pos; }
+ return this.pos > start
+ };
+ StringStream.prototype.skipToEnd = function () {this.pos = this.string.length;};
+ StringStream.prototype.skipTo = function (ch) {
+ var found = this.string.indexOf(ch, this.pos);
+ if (found > -1) {this.pos = found; return true}
+ };
+ StringStream.prototype.backUp = function (n) {this.pos -= n;};
+ StringStream.prototype.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)
+ };
+ StringStream.prototype.indentation = function () {
+ return countColumn(this.string, null, this.tabSize) -
+ (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0)
+ };
+ StringStream.prototype.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
+ }
+ };
+ StringStream.prototype.current = function (){return this.string.slice(this.start, this.pos)};
+ StringStream.prototype.hideFirstChars = function (n, inner) {
+ this.lineStart += n;
+ try { return inner() }
+ finally { this.lineStart -= n; }
+ };
+ StringStream.prototype.lookAhead = function (n) {
+ var oracle = this.lineOracle;
+ return oracle && oracle.lookAhead(n)
+ };
+ StringStream.prototype.baseToken = function () {
+ var oracle = this.lineOracle;
+ return oracle && oracle.baseToken(this.pos)
+ };
+
+ // 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.") }
+ var chunk = doc;
+ while (!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); }); // iter aborts when callback returns truthy value
+ 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$1 = 0; i$1 < chunk.children.length; ++i$1) {
+ var child = chunk.children[i$1], ch = child.height;
+ if (h < ch) { chunk = child; continue outer }
+ h -= ch;
+ n += child.chunkSize();
+ }
+ return n
+ } while (!chunk.lines)
+ var i = 0;
+ for (; i < chunk.lines.length; ++i) {
+ var line = chunk.lines[i], lh = line.height;
+ if (h < lh) { break }
+ h -= lh;
+ }
+ return n + i
+ }
+
+ function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size}
+
+ function lineNumberFor(options, i) {
+ return String(options.lineNumberFormatter(i + options.firstLineNumber))
+ }
+
+ // A Pos instance represents a position within the text.
+ function Pos(line, ch, sticky) {
+ if ( sticky === void 0 ) sticky = null;
+
+ if (!(this instanceof Pos)) { return new Pos(line, ch, sticky) }
+ this.line = line;
+ this.ch = ch;
+ this.sticky = sticky;
+ }
+
+ // Compare two positions, return 0 if they are the same, a negative
+ // number when a is less, and a positive number otherwise.
+ function cmp(a, b) { return a.line - b.line || a.ch - b.ch }
+
+ function equalCursorPos(a, b) { return a.sticky == b.sticky && cmp(a, b) == 0 }
+
+ 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 }
+
+ // 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 clipPosArray(doc, array) {
+ var out = [];
+ for (var i = 0; i < array.length; i++) { out[i] = clipPos(doc, array[i]); }
+ return out
+ }
+
+ var SavedContext = function(state, lookAhead) {
+ this.state = state;
+ this.lookAhead = lookAhead;
+ };
+
+ var Context = function(doc, state, line, lookAhead) {
+ this.state = state;
+ this.doc = doc;
+ this.line = line;
+ this.maxLookAhead = lookAhead || 0;
+ this.baseTokens = null;
+ this.baseTokenPos = 1;
+ };
+
+ Context.prototype.lookAhead = function (n) {
+ var line = this.doc.getLine(this.line + n);
+ if (line != null && n > this.maxLookAhead) { this.maxLookAhead = n; }
+ return line
+ };
+
+ Context.prototype.baseToken = function (n) {
+ if (!this.baseTokens) { return null }
+ while (this.baseTokens[this.baseTokenPos] <= n)
+ { this.baseTokenPos += 2; }
+ var type = this.baseTokens[this.baseTokenPos + 1];
+ return {type: type && type.replace(/( |^)overlay .*/, ""),
+ size: this.baseTokens[this.baseTokenPos] - n}
+ };
+
+ Context.prototype.nextLine = function () {
+ this.line++;
+ if (this.maxLookAhead > 0) { this.maxLookAhead--; }
+ };
+
+ Context.fromSaved = function (doc, saved, line) {
+ if (saved instanceof SavedContext)
+ { return new Context(doc, copyState(doc.mode, saved.state), line, saved.lookAhead) }
+ else
+ { return new Context(doc, copyState(doc.mode, saved), line) }
+ };
+
+ Context.prototype.save = function (copy) {
+ var state = copy !== false ? copyState(this.doc.mode, this.state) : this.state;
+ return this.maxLookAhead > 0 ? new SavedContext(state, this.maxLookAhead) : state
+ };
+
+
+ // 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, context, 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], lineClasses = {};
+ // Compute the base array of styles
+ runMode(cm, line.text, cm.doc.mode, context, function (end, style) { return st.push(end, style); },
+ lineClasses, forceToEnd);
+ var state = context.state;
+
+ // Run overlays, adjust style array.
+ var loop = function ( o ) {
+ context.baseTokens = st;
+ var overlay = cm.state.overlays[o], i = 1, at = 0;
+ context.state = true;
+ runMode(cm, line.text, overlay.mode, context, 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, "overlay " + style);
+ i = start + 2;
+ } else {
+ for (; start < i; start += 2) {
+ var cur = st[start+1];
+ st[start+1] = (cur ? cur + " " : "") + "overlay " + style;
+ }
+ }
+ }, lineClasses);
+ context.state = state;
+ context.baseTokens = null;
+ context.baseTokenPos = 1;
+ };
+
+ for (var o = 0; o < cm.state.overlays.length; ++o) loop( o );
+
+ return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}
+ }
+
+ function getLineStyles(cm, line, updateFrontier) {
+ if (!line.styles || line.styles[0] != cm.state.modeGen) {
+ var context = getContextBefore(cm, lineNo(line));
+ var resetState = line.text.length > cm.options.maxHighlightLength && copyState(cm.doc.mode, context.state);
+ var result = highlightLine(cm, line, context);
+ if (resetState) { context.state = resetState; }
+ line.stateAfter = context.save(!resetState);
+ line.styles = result.styles;
+ if (result.classes) { line.styleClasses = result.classes; }
+ else if (line.styleClasses) { line.styleClasses = null; }
+ if (updateFrontier === cm.doc.highlightFrontier)
+ { cm.doc.modeFrontier = Math.max(cm.doc.modeFrontier, ++cm.doc.highlightFrontier); }
+ }
+ return line.styles
+ }
+
+ function getContextBefore(cm, n, precise) {
+ var doc = cm.doc, display = cm.display;
+ if (!doc.mode.startState) { return new Context(doc, true, n) }
+ var start = findStartLine(cm, n, precise);
+ var saved = start > doc.first && getLine(doc, start - 1).stateAfter;
+ var context = saved ? Context.fromSaved(doc, saved, start) : new Context(doc, startState(doc.mode), start);
+
+ doc.iter(start, n, function (line) {
+ processLine(cm, line.text, context);
+ var pos = context.line;
+ line.stateAfter = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo ? context.save() : null;
+ context.nextLine();
+ });
+ if (precise) { doc.modeFrontier = context.line; }
+ return context
+ }
+
+ // 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, context, startAt) {
+ var mode = cm.doc.mode;
+ var stream = new StringStream(text, cm.options.tabSize, context);
+ stream.start = stream.pos = startAt || 0;
+ if (text == "") { callBlankLine(mode, context.state); }
+ while (!stream.eol()) {
+ readToken(mode, stream, context.state);
+ stream.start = stream.pos;
+ }
+ }
+
+ function callBlankLine(mode, state) {
+ if (mode.blankLine) { return mode.blankLine(state) }
+ if (!mode.innerMode) { return }
+ var inner = innerMode(mode, state);
+ if (inner.mode.blankLine) { return inner.mode.blankLine(inner.state) }
+ }
+
+ function readToken(mode, stream, state, inner) {
+ for (var i = 0; i < 10; i++) {
+ if (inner) { inner[0] = innerMode(mode, state).mode; }
+ var style = mode.token(stream, state);
+ if (stream.pos > stream.start) { return style }
+ }
+ throw new Error("Mode " + mode.name + " failed to advance stream.")
+ }
+
+ var Token = function(stream, type, state) {
+ this.start = stream.start; this.end = stream.pos;
+ this.string = stream.current();
+ this.type = type || null;
+ this.state = state;
+ };
+
+ // Utility for getTokenAt and getLineTokens
+ function takeToken(cm, pos, precise, asArray) {
+ var doc = cm.doc, mode = doc.mode, style;
+ pos = clipPos(doc, pos);
+ var line = getLine(doc, pos.line), context = getContextBefore(cm, pos.line, precise);
+ var stream = new StringStream(line.text, cm.options.tabSize, context), tokens;
+ if (asArray) { tokens = []; }
+ while ((asArray || stream.pos < pos.ch) && !stream.eol()) {
+ stream.start = stream.pos;
+ style = readToken(mode, stream, context.state);
+ if (asArray) { tokens.push(new Token(stream, style, copyState(doc.mode, context.state))); }
+ }
+ return asArray ? tokens : new Token(stream, style, context.state)
+ }
+
+ function extractLineClasses(type, output) {
+ if (type) { for (;;) {
+ var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/);
+ if (!lineClass) { break }
+ type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length);
+ var prop = lineClass[1] ? "bgClass" : "textClass";
+ if (output[prop] == null)
+ { output[prop] = lineClass[2]; }
+ else if (!(new RegExp("(?:^|\\s)" + lineClass[2] + "(?:$|\\s)")).test(output[prop]))
+ { output[prop] += " " + lineClass[2]; }
+ } }
+ return type
+ }
+
+ // Run the given mode's parser over a line, calling f for each token.
+ function runMode(cm, text, mode, context, f, lineClasses, 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, context), style;
+ var inner = cm.options.addModeClass && [null];
+ if (text == "") { extractLineClasses(callBlankLine(mode, context.state), lineClasses); }
+ while (!stream.eol()) {
+ if (stream.pos > cm.options.maxHighlightLength) {
+ flattenSpans = false;
+ if (forceToEnd) { processLine(cm, text, context, stream.pos); }
+ stream.pos = text.length;
+ style = null;
+ } else {
+ style = extractLineClasses(readToken(mode, stream, context.state, inner), lineClasses);
+ }
+ if (inner) {
+ var mName = inner[0].name;
+ if (mName) { style = "m-" + (style ? mName + " " + style : mName); }
+ }
+ if (!flattenSpans || curStyle != style) {
+ while (curStart < stream.start) {
+ curStart = Math.min(stream.start, curStart + 5000);
+ f(curStart, curStyle);
+ }
+ curStyle = style;
+ }
+ stream.start = stream.pos;
+ }
+ while (curStart < stream.pos) {
+ // Webkit seems to refuse to render text nodes longer than 57444
+ // characters, and returns inaccurate measurements in nodes
+ // starting around 5000 chars.
+ var pos = Math.min(stream.pos, curStart + 5000);
+ f(pos, curStyle);
+ curStart = pos;
+ }
+ }
+
+ // 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), after = line.stateAfter;
+ if (after && (!precise || search + (after instanceof SavedContext ? after.lookAhead : 0) <= doc.modeFrontier))
+ { return search }
+ var indented = countColumn(line.text, null, cm.options.tabSize);
+ if (minline == null || minindent > indented) {
+ minline = search - 1;
+ minindent = indented;
+ }
+ }
+ return minline
+ }
+
+ function retreatFrontier(doc, n) {
+ doc.modeFrontier = Math.min(doc.modeFrontier, n);
+ if (doc.highlightFrontier < n - 10) { return }
+ var start = doc.first;
+ for (var line = n - 1; line > start; line--) {
+ var saved = getLine(doc, line).stateAfter;
+ // change is on 3
+ // state on line 1 looked ahead 2 -- so saw 3
+ // test 1 + 2 < 3 should cover this
+ if (saved && (!(saved instanceof SavedContext) || line + saved.lookAhead < n)) {
+ start = line + 1;
+ break
+ }
+ }
+ doc.highlightFrontier = Math.min(doc.highlightFrontier, start);
+ }
+
+ // Optimize some code when these features are not used.
+ var sawReadOnlySpans = false, sawCollapsedSpans = false;
+
+ function seeReadOnlySpans() {
+ sawReadOnlySpans = true;
+ }
+
+ function seeCollapsedSpans() {
+ sawCollapsedSpans = true;
+ }
+
+ // 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) {
+ var r;
+ for (var 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) {
+ var nw;
+ if (old) { for (var i = 0; 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) {
+ var nw;
+ if (old) { for (var i = 0; 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) {
+ if (change.full) { return null }
+ 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$1 = 0; i$1 < last.length; ++i$1) {
+ var span$1 = last[i$1];
+ if (span$1.to != null) { span$1.to += offset; }
+ if (span$1.from == null) {
+ var found$1 = getMarkedSpanFor(first, span$1.marker);
+ if (!found$1) {
+ span$1.from = offset;
+ if (sameLine) { (first || (first = [])).push(span$1); }
+ }
+ } else {
+ span$1.from += offset;
+ if (sameLine) { (first || (first = [])).push(span$1); }
+ }
+ }
+ }
+ // 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$2 = 0; i$2 < first.length; ++i$2)
+ { if (first[i$2].to == null)
+ { (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i$2].marker, null, null)); } } }
+ for (var i$3 = 0; i$3 < gap; ++i$3)
+ { 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 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 - 3;
+ }
+ }
+ 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 = (void 0), 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) }
+
+ function collapsedSpanAround(line, ch) {
+ var sps = sawCollapsedSpans && line.markedSpans, found;
+ if (sps) { for (var i = 0; i < sps.length; ++i) {
+ var sp = sps[i];
+ if (sp.marker.collapsed && (sp.from == null || sp.from < ch) && (sp.to == null || sp.to > ch) &&
+ (!found || compareCollapsedMarkers(found, sp.marker) < 0)) { found = sp.marker; }
+ } }
+ return found
+ }
+
+ // 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 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.to, from) >= 0 : cmp(found.to, from) > 0) ||
+ fromCmp >= 0 && (sp.marker.inclusiveRight && marker.inclusiveLeft ? cmp(found.from, to) <= 0 : cmp(found.from, to) < 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
+ }
+
+ function visualLineEnd(line) {
+ var merged;
+ while (merged = collapsedSpanAtEnd(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 = (void 0), 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 = (void 0), 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 }
+ }
+ }
+
+ // 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$1 = 0; i$1 < p.children.length; ++i$1) {
+ var cur = p.children[i$1];
+ if (cur == chunk) { break }
+ else { h += cur.height; }
+ }
+ }
+ return h
+ }
+
+ // 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$1 = merged.find(0, true);
+ len -= cur.text.length - found$1.from.ch;
+ cur = found$1.to.line;
+ len += cur.text.length - found$1.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;
+ }
+ });
+ }
+
+ // LINE DATA STRUCTURE
+
+ // Line objects. These hold state related to a line, including
+ // highlighting info (the styles array).
+ var Line = function(text, markedSpans, estimateHeight) {
+ this.text = text;
+ attachMarkedSpans(this, markedSpans);
+ this.height = estimateHeight ? estimateHeight(this) : 1;
+ };
+
+ Line.prototype.lineNo = function () { return lineNo(this) };
+ eventMixin(Line);
+
+ // 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);
+ }
+
+ // 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, options) {
+ if (!style || /^\s*$/.test(style)) { return null }
+ var cache = 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 = eltP("span", null, null, webkit ? "padding-right: .1px" : null);
+ var builder = {pre: eltP("pre", [content], "CodeMirror-line"), content: content,
+ col: 0, pos: 0, cm: cm,
+ trailingSpace: false,
+ splitSpaces: cm.getOption("lineWrapping")};
+ 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 = (void 0);
+ builder.pos = 0;
+ builder.addToken = buildToken;
+ // Optionally wire in some hacks into the token-rendering
+ // algorithm, to deal with browser quirks.
+ if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line, cm.doc.direction)))
+ { builder.addToken = buildTokenBadBidi(builder.addToken, order); }
+ builder.map = [];
+ var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line);
+ insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate));
+ if (line.styleClasses) {
+ if (line.styleClasses.bgClass)
+ { builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); }
+ if (line.styleClasses.textClass)
+ { builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); }
+ }
+
+ // 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({});
+ }
+ }
+
+ // See issue #2901
+ if (webkit) {
+ var last = builder.content.lastChild;
+ if (/\bcm-tab\b/.test(last.className) || (last.querySelector && last.querySelector(".cm-tab")))
+ { builder.content.className = "cm-tab-wrap-hack"; }
+ }
+
+ signal(cm, "renderLine", cm, lineView.line, builder.pre);
+ if (builder.pre.className)
+ { builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); }
+
+ return builder
+ }
+
+ function defaultSpecialCharPlaceholder(ch) {
+ var token = elt("span", "\u2022", "cm-invalidchar");
+ token.title = "\\u" + ch.charCodeAt(0).toString(16);
+ token.setAttribute("aria-label", token.title);
+ 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, css, attributes) {
+ if (!text) { return }
+ var displayText = builder.splitSpaces ? splitSpaces(text, builder.trailingSpace) : text;
+ var special = builder.cm.state.specialChars, mustWrap = false;
+ var content;
+ if (!special.test(text)) {
+ builder.col += text.length;
+ content = document.createTextNode(displayText);
+ builder.map.push(builder.pos, builder.pos + text.length, content);
+ if (ie && ie_version < 9) { mustWrap = true; }
+ builder.pos += text.length;
+ } else {
+ content = document.createDocumentFragment();
+ var 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(displayText.slice(pos, pos + skipped));
+ if (ie && ie_version < 9) { 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;
+ var txt$1 = (void 0);
+ if (m[0] == "\t") {
+ var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize;
+ txt$1 = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab"));
+ txt$1.setAttribute("role", "presentation");
+ txt$1.setAttribute("cm-text", "\t");
+ builder.col += tabWidth;
+ } else if (m[0] == "\r" || m[0] == "\n") {
+ txt$1 = content.appendChild(elt("span", m[0] == "\r" ? "\u240d" : "\u2424", "cm-invalidchar"));
+ txt$1.setAttribute("cm-text", m[0]);
+ builder.col += 1;
+ } else {
+ txt$1 = builder.cm.options.specialCharPlaceholder(m[0]);
+ txt$1.setAttribute("cm-text", m[0]);
+ if (ie && ie_version < 9) { content.appendChild(elt("span", [txt$1])); }
+ else { content.appendChild(txt$1); }
+ builder.col += 1;
+ }
+ builder.map.push(builder.pos, builder.pos + 1, txt$1);
+ builder.pos++;
+ }
+ }
+ builder.trailingSpace = displayText.charCodeAt(text.length - 1) == 32;
+ if (style || startStyle || endStyle || mustWrap || css || attributes) {
+ var fullStyle = style || "";
+ if (startStyle) { fullStyle += startStyle; }
+ if (endStyle) { fullStyle += endStyle; }
+ var token = elt("span", [content], fullStyle, css);
+ if (attributes) {
+ for (var attr in attributes) { if (attributes.hasOwnProperty(attr) && attr != "style" && attr != "class")
+ { token.setAttribute(attr, attributes[attr]); } }
+ }
+ return builder.content.appendChild(token)
+ }
+ builder.content.appendChild(content);
+ }
+
+ // Change some spaces to NBSP to prevent the browser from collapsing
+ // trailing spaces at the end of a line when rendering text (issue #1362).
+ function splitSpaces(text, trailingBefore) {
+ if (text.length > 1 && !/ /.test(text)) { return text }
+ var spaceBefore = trailingBefore, result = "";
+ for (var i = 0; i < text.length; i++) {
+ var ch = text.charAt(i);
+ if (ch == " " && spaceBefore && (i == text.length - 1 || text.charCodeAt(i + 1) == 32))
+ { ch = "\u00a0"; }
+ result += ch;
+ spaceBefore = ch == " ";
+ }
+ return result
+ }
+
+ // Work around nonsense dimensions being reported for stretches of
+ // right-to-left text.
+ function buildTokenBadBidi(inner, order) {
+ return function (builder, text, style, startStyle, endStyle, css, attributes) {
+ 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
+ var part = (void 0);
+ for (var i = 0; i < order.length; i++) {
+ part = order[i];
+ if (part.to > start && part.from <= start) { break }
+ }
+ if (part.to >= end) { return inner(builder, text, style, startStyle, endStyle, css, attributes) }
+ inner(builder, text.slice(0, part.to - start), style, startStyle, null, css, attributes);
+ 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); }
+ if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) {
+ if (!widget)
+ { widget = builder.content.appendChild(document.createElement("span")); }
+ widget.setAttribute("cm-marker", marker.id);
+ }
+ if (widget) {
+ builder.cm.display.input.setUneditable(widget);
+ builder.content.appendChild(widget);
+ }
+ builder.pos += size;
+ builder.trailingSpace = false;
+ }
+
+ // 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 = 1; i$1 < styles.length; i$1+=2)
+ { builder.addToken(builder, allText.slice(at, at = styles[i$1]), interpretTokenStyle(styles[i$1+1], builder.cm.options)); }
+ return
+ }
+
+ var len = allText.length, pos = 0, i = 1, text = "", style, css;
+ var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, collapsed, attributes;
+ for (;;) {
+ if (nextChange == pos) { // Update current marker set
+ spanStyle = spanEndStyle = spanStartStyle = css = "";
+ attributes = null;
+ collapsed = null; nextChange = Infinity;
+ var foundBookmarks = [], endStyles = (void 0);
+ for (var j = 0; j < spans.length; ++j) {
+ var sp = spans[j], m = sp.marker;
+ if (m.type == "bookmark" && sp.from == pos && m.widgetNode) {
+ foundBookmarks.push(m);
+ } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) {
+ if (sp.to != null && sp.to != pos && nextChange > sp.to) {
+ nextChange = sp.to;
+ spanEndStyle = "";
+ }
+ if (m.className) { spanStyle += " " + m.className; }
+ if (m.css) { css = (css ? css + ";" : "") + m.css; }
+ if (m.startStyle && sp.from == pos) { spanStartStyle += " " + m.startStyle; }
+ if (m.endStyle && sp.to == nextChange) { (endStyles || (endStyles = [])).push(m.endStyle, sp.to); }
+ // support for the old title property
+ // https://github.com/codemirror/CodeMirror/pull/5673
+ if (m.title) { (attributes || (attributes = {})).title = m.title; }
+ if (m.attributes) {
+ for (var attr in m.attributes)
+ { (attributes || (attributes = {}))[attr] = m.attributes[attr]; }
+ }
+ if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0))
+ { collapsed = sp; }
+ } else if (sp.from > pos && nextChange > sp.from) {
+ nextChange = sp.from;
+ }
+ }
+ if (endStyles) { for (var j$1 = 0; j$1 < endStyles.length; j$1 += 2)
+ { if (endStyles[j$1 + 1] == nextChange) { spanEndStyle += " " + endStyles[j$1]; } } }
+
+ if (!collapsed || collapsed.from == pos) { for (var j$2 = 0; j$2 < foundBookmarks.length; ++j$2)
+ { buildCollapsedSpan(builder, 0, foundBookmarks[j$2]); } }
+ 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.to == pos) { collapsed = false; }
+ }
+ }
+ 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 : "", css, attributes);
+ }
+ 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.cm.options);
+ }
+ }
+ }
+
+
+ // 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
+ }
+
+ var operationGroup = null;
+
+ function pushOperation(op) {
+ if (operationGroup) {
+ operationGroup.ops.push(op);
+ } else {
+ op.ownsGroup = operationGroup = {
+ ops: [op],
+ delayedCallbacks: []
+ };
+ }
+ }
+
+ function fireCallbacksForOps(group) {
+ // Calls delayed callbacks and cursorActivity handlers until no
+ // new ones appear
+ var callbacks = group.delayedCallbacks, i = 0;
+ do {
+ for (; i < callbacks.length; i++)
+ { callbacks[i].call(null); }
+ for (var j = 0; j < group.ops.length; j++) {
+ var op = group.ops[j];
+ if (op.cursorActivityHandlers)
+ { while (op.cursorActivityCalled < op.cursorActivityHandlers.length)
+ { op.cursorActivityHandlers[op.cursorActivityCalled++].call(null, op.cm); } }
+ }
+ } while (i < callbacks.length)
+ }
+
+ function finishOperation(op, endCb) {
+ var group = op.ownsGroup;
+ if (!group) { return }
+
+ try { fireCallbacksForOps(group); }
+ finally {
+ operationGroup = null;
+ endCb(group);
+ }
+ }
+
+ var orphanDelayedCallbacks = null;
+
+ // 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.
+ function signalLater(emitter, type /*, values...*/) {
+ var arr = getHandlers(emitter, type);
+ if (!arr.length) { return }
+ var args = Array.prototype.slice.call(arguments, 2), list;
+ if (operationGroup) {
+ list = operationGroup.delayedCallbacks;
+ } else if (orphanDelayedCallbacks) {
+ list = orphanDelayedCallbacks;
+ } else {
+ list = orphanDelayedCallbacks = [];
+ setTimeout(fireOrphanDelayed, 0);
+ }
+ var loop = function ( i ) {
+ list.push(function () { return arr[i].apply(null, args); });
+ };
+
+ for (var i = 0; i < arr.length; ++i)
+ loop( i );
+ }
+
+ function fireOrphanDelayed() {
+ var delayed = orphanDelayedCallbacks;
+ orphanDelayedCallbacks = null;
+ for (var i = 0; i < delayed.length; ++i) { delayed[i](); }
+ }
+
+ // 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(cm, lineView); }
+ else if (type == "widget") { updateLineWidgets(cm, 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 && ie_version < 8) { lineView.node.style.zIndex = 2; }
+ }
+ return lineView.node
+ }
+
+ function updateLineBackground(cm, 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);
+ cm.display.input.setUneditable(lineView.background);
+ }
+ }
+
+ // 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(cm, lineView);
+ } else if (cls) {
+ lineView.text.className = cls;
+ }
+ }
+
+ function updateLineClasses(cm, lineView) {
+ updateLineBackground(cm, 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;
+ }
+ if (lineView.gutterBackground) {
+ lineView.node.removeChild(lineView.gutterBackground);
+ lineView.gutterBackground = null;
+ }
+ if (lineView.line.gutterClass) {
+ var wrap = ensureLineWrapped(lineView);
+ lineView.gutterBackground = elt("div", null, "CodeMirror-gutter-background " + lineView.line.gutterClass,
+ ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px; width: " + (dims.gutterTotalWidth) + "px"));
+ cm.display.input.setUneditable(lineView.gutterBackground);
+ wrap.insertBefore(lineView.gutterBackground, lineView.text);
+ }
+ var markers = lineView.line.gutterMarkers;
+ if (cm.options.lineNumbers || markers) {
+ var wrap$1 = ensureLineWrapped(lineView);
+ var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", ("left: " + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + "px"));
+ cm.display.input.setUneditable(gutterWrap);
+ wrap$1.insertBefore(gutterWrap, lineView.text);
+ if (lineView.line.gutterClass)
+ { gutterWrap.className += " " + lineView.line.gutterClass; }
+ 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.display.gutterSpecs.length; ++k) {
+ var id = cm.display.gutterSpecs[k].className, 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(cm, lineView, dims) {
+ if (lineView.alignable) { lineView.alignable = null; }
+ var isWidget = classTest("CodeMirror-linewidget");
+ for (var node = lineView.node.firstChild, next = (void 0); node; node = next) {
+ next = node.nextSibling;
+ if (isWidget.test(node.className)) { lineView.node.removeChild(node); }
+ }
+ insertLineWidgets(cm, 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(cm, lineView);
+ updateLineGutter(cm, lineView, lineN, dims);
+ insertLineWidgets(cm, 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(cm, lineView, dims) {
+ insertLineWidgetsFor(cm, lineView.line, lineView, dims, true);
+ if (lineView.rest) { for (var i = 0; i < lineView.rest.length; i++)
+ { insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); } }
+ }
+
+ function insertLineWidgetsFor(cm, 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" + (widget.className ? " " + widget.className : ""));
+ if (!widget.handleMouseEvents) { node.setAttribute("cm-ignore-events", "true"); }
+ positionLineWidget(widget, node, lineView, dims);
+ cm.display.input.setUneditable(node);
+ 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"; }
+ }
+ }
+
+ function widgetHeight(widget) {
+ if (widget.height != null) { return widget.height }
+ var cm = widget.doc.cm;
+ if (!cm) { return 0 }
+ if (!contains(document.body, widget.node)) {
+ var parentStyle = "position: relative;";
+ if (widget.coverGutter)
+ { parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; }
+ if (widget.noHScroll)
+ { parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; }
+ removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle));
+ }
+ return widget.height = widget.node.parentNode.offsetHeight
+ }
+
+ // 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.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") ||
+ (n.parentNode == display.sizer && n != display.mover))
+ { return true }
+ }
+ }
+
+ // 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", "CodeMirror-line-like"));
+ var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle;
+ var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)};
+ if (!isNaN(data.left) && !isNaN(data.right)) { display.cachedPaddingH = data; }
+ return data
+ }
+
+ function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth }
+ function displayWidth(cm) {
+ return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth
+ }
+ function displayHeight(cm) {
+ return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight
+ }
+
+ // 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 && displayWidth(cm);
+ 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$1 = 0; i$1 < lineView.rest.length; i$1++)
+ { if (lineNo(lineView.rest[i$1]) > lineN)
+ { return {map: lineView.measure.maps[i$1], cache: lineView.measure.caches[i$1], 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));
+ cm.curOp.forceUpdate = true;
+ }
+ 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, varHeight) {
+ 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: varHeight ? found.rtop : found.top,
+ bottom: varHeight ? found.rbottom : found.bottom}
+ }
+
+ var nullRect = {left: 0, right: 0, top: 0, bottom: 0};
+
+ function nodeAndOffsetInLineMap(map, ch, bias) {
+ var node, start, end, collapse, mStart, mEnd;
+ // 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) {
+ 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
+ }
+ }
+ return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}
+ }
+
+ function getUsefulRect(rects, bias) {
+ var rect = nullRect;
+ if (bias == "left") { for (var i = 0; i < rects.length; i++) {
+ if ((rect = rects[i]).left != rect.right) { break }
+ } } else { for (var i$1 = rects.length - 1; i$1 >= 0; i$1--) {
+ if ((rect = rects[i$1]).left != rect.right) { break }
+ } }
+ return rect
+ }
+
+ function measureCharInner(cm, prepared, ch, bias) {
+ var place = nodeAndOffsetInLineMap(prepared.map, ch, bias);
+ var node = place.node, start = place.start, end = place.end, collapse = place.collapse;
+
+ var rect;
+ if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates.
+ for (var i$1 = 0; i$1 < 4; i$1++) { // Retry a maximum of 4 times when nonsense rectangles are returned
+ while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) { --start; }
+ while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) { ++end; }
+ if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart)
+ { rect = node.parentNode.getBoundingClientRect(); }
+ else
+ { rect = getUsefulRect(range(node, start, end).getClientRects(), bias); }
+ if (rect.left || rect.right || start == 0) { break }
+ end = start;
+ start = start - 1;
+ collapse = "right";
+ }
+ if (ie && ie_version < 11) { rect = maybeUpdateRectForZooming(cm.display.measure, rect); }
+ } 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 && ie_version < 9 && !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 rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top;
+ var mid = (rtop + rbot) / 2;
+ var heights = prepared.view.measure.heights;
+ var i = 0;
+ for (; i < heights.length - 1; i++)
+ { if (mid < heights[i]) { break } }
+ var 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; }
+ if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; }
+
+ return result
+ }
+
+ // Work around problem with bounding client rects on ranges being
+ // returned incorrectly when zoomed on IE10 and below.
+ function maybeUpdateRectForZooming(measure, rect) {
+ if (!window.screen || screen.logicalXDPI == null ||
+ screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure))
+ { return rect }
+ var scaleX = screen.logicalXDPI / screen.deviceXDPI;
+ var scaleY = screen.logicalYDPI / screen.deviceYDPI;
+ return {left: rect.left * scaleX, right: rect.right * scaleX,
+ top: rect.top * scaleY, bottom: rect.bottom * scaleY}
+ }
+
+ 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() {
+ // Work around https://bugs.chromium.org/p/chromium/issues/detail?id=489206
+ // which causes page_Offset and bounding client rects to use
+ // different reference viewports and invalidate our calculations.
+ if (chrome && android) { return -(document.body.getBoundingClientRect().left - parseInt(getComputedStyle(document.body).marginLeft)) }
+ return window.pageXOffset || (document.documentElement || document.body).scrollLeft
+ }
+ function pageScrollY() {
+ if (chrome && android) { return -(document.body.getBoundingClientRect().top - parseInt(getComputedStyle(document.body).marginTop)) }
+ return window.pageYOffset || (document.documentElement || document.body).scrollTop
+ }
+
+ function widgetTopHeight(lineObj) {
+ var height = 0;
+ if (lineObj.widgets) { for (var i = 0; i < lineObj.widgets.length; ++i) { if (lineObj.widgets[i].above)
+ { height += widgetHeight(lineObj.widgets[i]); } } }
+ return height
+ }
+
+ // 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), "window",
+ // or "page".
+ function intoCoordSystem(cm, lineObj, rect, context, includeWidgets) {
+ if (!includeWidgets) {
+ var height = widgetTopHeight(lineObj);
+ rect.top += height; rect.bottom += height;
+ }
+ 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.
+ // A cursor Pos(line, char, "before") is on the same visual line as `char - 1`
+ // and after `char - 1` in writing order of `char - 1`
+ // A cursor Pos(line, char, "after") is on the same visual line as `char`
+ // and before `char` in writing order of `char`
+ // Examples (upper-case letters are RTL, lower-case are LTR):
+ // Pos(0, 1, ...)
+ // before after
+ // ab a|b a|b
+ // aB a|B aB|
+ // Ab |Ab A|b
+ // AB B|A B|A
+ // Every position after the last character on a line is considered to stick
+ // to the last character on the line.
+ function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) {
+ 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", varHeight);
+ if (right) { m.left = m.right; } else { m.right = m.left; }
+ return intoCoordSystem(cm, lineObj, m, context)
+ }
+ var order = getOrder(lineObj, cm.doc.direction), ch = pos.ch, sticky = pos.sticky;
+ if (ch >= lineObj.text.length) {
+ ch = lineObj.text.length;
+ sticky = "before";
+ } else if (ch <= 0) {
+ ch = 0;
+ sticky = "after";
+ }
+ if (!order) { return get(sticky == "before" ? ch - 1 : ch, sticky == "before") }
+
+ function getBidi(ch, partPos, invert) {
+ var part = order[partPos], right = part.level == 1;
+ return get(invert ? ch - 1 : ch, right != invert)
+ }
+ var partPos = getBidiPartAt(order, ch, sticky);
+ var other = bidiOther;
+ var val = getBidi(ch, partPos, sticky == "before");
+ if (other != null) { val.other = getBidi(ch, other, sticky != "before"); }
+ 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, sticky, outside, xRel) {
+ var pos = Pos(line, ch, sticky);
+ pos.xRel = xRel;
+ if (outside) { pos.outside = outside; }
+ 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, null, -1, -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, null, 1, 1) }
+ if (x < 0) { x = 0; }
+
+ var lineObj = getLine(doc, lineN);
+ for (;;) {
+ var found = coordsCharInner(cm, lineObj, lineN, x, y);
+ var collapsed = collapsedSpanAround(lineObj, found.ch + (found.xRel > 0 || found.outside > 0 ? 1 : 0));
+ if (!collapsed) { return found }
+ var rangeEnd = collapsed.find(1);
+ if (rangeEnd.line == lineN) { return rangeEnd }
+ lineObj = getLine(doc, lineN = rangeEnd.line);
+ }
+ }
+
+ function wrappedLineExtent(cm, lineObj, preparedMeasure, y) {
+ y -= widgetTopHeight(lineObj);
+ var end = lineObj.text.length;
+ var begin = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch - 1).bottom <= y; }, end, 0);
+ end = findFirst(function (ch) { return measureCharPrepared(cm, preparedMeasure, ch).top > y; }, begin, end);
+ return {begin: begin, end: end}
+ }
+
+ function wrappedLineExtentChar(cm, lineObj, preparedMeasure, target) {
+ if (!preparedMeasure) { preparedMeasure = prepareMeasureForLine(cm, lineObj); }
+ var targetTop = intoCoordSystem(cm, lineObj, measureCharPrepared(cm, preparedMeasure, target), "line").top;
+ return wrappedLineExtent(cm, lineObj, preparedMeasure, targetTop)
+ }
+
+ // Returns true if the given side of a box is after the given
+ // coordinates, in top-to-bottom, left-to-right order.
+ function boxIsAfter(box, x, y, left) {
+ return box.bottom <= y ? false : box.top > y ? true : (left ? box.left : box.right) > x
+ }
+
+ function coordsCharInner(cm, lineObj, lineNo, x, y) {
+ // Move y into line-local coordinate space
+ y -= heightAtLine(lineObj);
+ var preparedMeasure = prepareMeasureForLine(cm, lineObj);
+ // When directly calling `measureCharPrepared`, we have to adjust
+ // for the widgets at this line.
+ var widgetHeight = widgetTopHeight(lineObj);
+ var begin = 0, end = lineObj.text.length, ltr = true;
+
+ var order = getOrder(lineObj, cm.doc.direction);
+ // If the line isn't plain left-to-right text, first figure out
+ // which bidi section the coordinates fall into.
+ if (order) {
+ var part = (cm.options.lineWrapping ? coordsBidiPartWrapped : coordsBidiPart)
+ (cm, lineObj, lineNo, preparedMeasure, order, x, y);
+ ltr = part.level != 1;
+ // The awkward -1 offsets are needed because findFirst (called
+ // on these below) will treat its first bound as inclusive,
+ // second as exclusive, but we want to actually address the
+ // characters in the part's range
+ begin = ltr ? part.from : part.to - 1;
+ end = ltr ? part.to : part.from - 1;
+ }
+
+ // A binary search to find the first character whose bounding box
+ // starts after the coordinates. If we run across any whose box wrap
+ // the coordinates, store that.
+ var chAround = null, boxAround = null;
+ var ch = findFirst(function (ch) {
+ var box = measureCharPrepared(cm, preparedMeasure, ch);
+ box.top += widgetHeight; box.bottom += widgetHeight;
+ if (!boxIsAfter(box, x, y, false)) { return false }
+ if (box.top <= y && box.left <= x) {
+ chAround = ch;
+ boxAround = box;
+ }
+ return true
+ }, begin, end);
+
+ var baseX, sticky, outside = false;
+ // If a box around the coordinates was found, use that
+ if (boxAround) {
+ // Distinguish coordinates nearer to the left or right side of the box
+ var atLeft = x - boxAround.left < boxAround.right - x, atStart = atLeft == ltr;
+ ch = chAround + (atStart ? 0 : 1);
+ sticky = atStart ? "after" : "before";
+ baseX = atLeft ? boxAround.left : boxAround.right;
+ } else {
+ // (Adjust for extended bound, if necessary.)
+ if (!ltr && (ch == end || ch == begin)) { ch++; }
+ // To determine which side to associate with, get the box to the
+ // left of the character and compare it's vertical position to the
+ // coordinates
+ sticky = ch == 0 ? "after" : ch == lineObj.text.length ? "before" :
+ (measureCharPrepared(cm, preparedMeasure, ch - (ltr ? 1 : 0)).bottom + widgetHeight <= y) == ltr ?
+ "after" : "before";
+ // Now get accurate coordinates for this place, in order to get a
+ // base X position
+ var coords = cursorCoords(cm, Pos(lineNo, ch, sticky), "line", lineObj, preparedMeasure);
+ baseX = coords.left;
+ outside = y < coords.top ? -1 : y >= coords.bottom ? 1 : 0;
+ }
+
+ ch = skipExtendingChars(lineObj.text, ch, 1);
+ return PosWithInfo(lineNo, ch, sticky, outside, x - baseX)
+ }
+
+ function coordsBidiPart(cm, lineObj, lineNo, preparedMeasure, order, x, y) {
+ // Bidi parts are sorted left-to-right, and in a non-line-wrapping
+ // situation, we can take this ordering to correspond to the visual
+ // ordering. This finds the first part whose end is after the given
+ // coordinates.
+ var index = findFirst(function (i) {
+ var part = order[i], ltr = part.level != 1;
+ return boxIsAfter(cursorCoords(cm, Pos(lineNo, ltr ? part.to : part.from, ltr ? "before" : "after"),
+ "line", lineObj, preparedMeasure), x, y, true)
+ }, 0, order.length - 1);
+ var part = order[index];
+ // If this isn't the first part, the part's start is also after
+ // the coordinates, and the coordinates aren't on the same line as
+ // that start, move one part back.
+ if (index > 0) {
+ var ltr = part.level != 1;
+ var start = cursorCoords(cm, Pos(lineNo, ltr ? part.from : part.to, ltr ? "after" : "before"),
+ "line", lineObj, preparedMeasure);
+ if (boxIsAfter(start, x, y, true) && start.top > y)
+ { part = order[index - 1]; }
+ }
+ return part
+ }
+
+ function coordsBidiPartWrapped(cm, lineObj, _lineNo, preparedMeasure, order, x, y) {
+ // In a wrapped line, rtl text on wrapping boundaries can do things
+ // that don't correspond to the ordering in our `order` array at
+ // all, so a binary search doesn't work, and we want to return a
+ // part that only spans one line so that the binary search in
+ // coordsCharInner is safe. As such, we first find the extent of the
+ // wrapped line, and then do a flat search in which we discard any
+ // spans that aren't on the line.
+ var ref = wrappedLineExtent(cm, lineObj, preparedMeasure, y);
+ var begin = ref.begin;
+ var end = ref.end;
+ if (/\s/.test(lineObj.text.charAt(end - 1))) { end--; }
+ var part = null, closestDist = null;
+ for (var i = 0; i < order.length; i++) {
+ var p = order[i];
+ if (p.from >= end || p.to <= begin) { continue }
+ var ltr = p.level != 1;
+ var endX = measureCharPrepared(cm, preparedMeasure, ltr ? Math.min(end, p.to) - 1 : Math.max(begin, p.from)).right;
+ // Weigh against spans ending before this, so that they are only
+ // picked if nothing ends after
+ var dist = endX < x ? x - endX + 1e9 : endX - x;
+ if (!part || closestDist > dist) {
+ part = p;
+ closestDist = dist;
+ }
+ }
+ if (!part) { part = order[order.length - 1]; }
+ // Clip the part to the wrapped line.
+ if (part.from < begin) { part = {from: begin, to: part.to, level: part.level}; }
+ if (part.to > end) { part = {from: part.from, to: end, level: part.level}; }
+ return part
+ }
+
+ var measureText;
+ // Compute the default text height.
+ function textHeight(display) {
+ if (display.cachedTextHeight != null) { return display.cachedTextHeight }
+ if (measureText == null) {
+ measureText = elt("pre", null, "CodeMirror-line-like");
+ // 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], "CodeMirror-line-like");
+ removeChildrenAndAdd(display.measure, pre);
+ var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10;
+ if (width > 2) { display.cachedCharWidth = width; }
+ return width || 10
+ }
+
+ // 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 = {};
+ var gutterLeft = d.gutters.clientLeft;
+ for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) {
+ var id = cm.display.gutterSpecs[i].className;
+ left[id] = n.offsetLeft + n.clientLeft + gutterLeft;
+ width[id] = n.clientWidth;
+ }
+ return {fixedPos: compensateForHScroll(d),
+ gutterTotalWidth: d.gutters.offsetWidth,
+ gutterLeft: left,
+ gutterWidth: width,
+ wrapperWidth: d.wrapper.clientWidth}
+ }
+
+ // 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
+ }
+
+ // 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); }
+ });
+ }
+
+ // 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 && e_target(e).getAttribute("cm-not-content") == "true") { 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$1) { return null }
+ var coords = coordsChar(cm, x, y), line;
+ if (forRect && coords.xRel > 0 && (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.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff));
+ }
+ return coords
+ }
+
+ // 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 }
+ }
+ }
+
+ // 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$1 = viewCuttingPoint(cm, from, from, -1);
+ if (cut$1) {
+ display.view = display.view.slice(0, cut$1.index);
+ display.viewTo = cut$1.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;
+ }
+
+ function viewCuttingPoint(cm, oldN, newN, dir) {
+ var index = findViewIndex(cm, oldN), diff, view = cm.display.view;
+ if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size)
+ { return {index: index, lineN: newN} }
+ var n = cm.display.viewFrom;
+ for (var i = 0; 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
+ }
+
+ function updateSelection(cm) {
+ cm.display.input.showSelection(cm.display.input.prepareSelection());
+ }
+
+ function prepareSelection(cm, primary) {
+ if ( primary === void 0 ) primary = true;
+
+ var doc = cm.doc, result = {};
+ var curFragment = result.cursors = document.createDocumentFragment();
+ var selFragment = result.selection = document.createDocumentFragment();
+
+ for (var i = 0; i < doc.sel.ranges.length; i++) {
+ if (!primary && i == doc.sel.primIndex) { continue }
+ var range = doc.sel.ranges[i];
+ if (range.from().line >= cm.display.viewTo || range.to().line < cm.display.viewFrom) { continue }
+ var collapsed = range.empty();
+ if (collapsed || cm.options.showCursorWhenSelecting)
+ { drawSelectionCursor(cm, range.head, curFragment); }
+ if (!collapsed)
+ { drawSelectionRange(cm, range, selFragment); }
+ }
+ return result
+ }
+
+ // Draws a cursor for the given range
+ function drawSelectionCursor(cm, head, output) {
+ var pos = cursorCoords(cm, head, "div", null, null, !cm.options.singleCursorHeightPerLine);
+
+ 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";
+ }
+ }
+
+ function cmpCoords(a, b) { return a.top - b.top || a.left - b.left }
+
+ // Draws the given range as a highlighted selection
+ function drawSelectionRange(cm, range, output) {
+ var display = cm.display, doc = cm.doc;
+ var fragment = document.createDocumentFragment();
+ var padding = paddingH(cm.display), leftSide = padding.left;
+ var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right;
+ var docLTR = doc.direction == "ltr";
+
+ function add(left, top, width, bottom) {
+ if (top < 0) { top = 0; }
+ top = Math.round(top);
+ bottom = Math.round(bottom);
+ fragment.appendChild(elt("div", null, "CodeMirror-selected", ("position: absolute; left: " + left + "px;\n top: " + top + "px; width: " + (width == null ? rightSide - left : width) + "px;\n 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)
+ }
+
+ function wrapX(pos, dir, side) {
+ var extent = wrappedLineExtentChar(cm, lineObj, null, pos);
+ var prop = (dir == "ltr") == (side == "after") ? "left" : "right";
+ var ch = side == "after" ? extent.begin : extent.end - (/\s/.test(lineObj.text.charAt(extent.end - 1)) ? 2 : 1);
+ return coords(ch, prop)[prop]
+ }
+
+ var order = getOrder(lineObj, doc.direction);
+ iterateBidiSections(order, fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir, i) {
+ var ltr = dir == "ltr";
+ var fromPos = coords(from, ltr ? "left" : "right");
+ var toPos = coords(to - 1, ltr ? "right" : "left");
+
+ var openStart = fromArg == null && from == 0, openEnd = toArg == null && to == lineLen;
+ var first = i == 0, last = !order || i == order.length - 1;
+ if (toPos.top - fromPos.top <= 3) { // Single line
+ var openLeft = (docLTR ? openStart : openEnd) && first;
+ var openRight = (docLTR ? openEnd : openStart) && last;
+ var left = openLeft ? leftSide : (ltr ? fromPos : toPos).left;
+ var right = openRight ? rightSide : (ltr ? toPos : fromPos).right;
+ add(left, fromPos.top, right - left, fromPos.bottom);
+ } else { // Multiple lines
+ var topLeft, topRight, botLeft, botRight;
+ if (ltr) {
+ topLeft = docLTR && openStart && first ? leftSide : fromPos.left;
+ topRight = docLTR ? rightSide : wrapX(from, dir, "before");
+ botLeft = docLTR ? leftSide : wrapX(to, dir, "after");
+ botRight = docLTR && openEnd && last ? rightSide : toPos.right;
+ } else {
+ topLeft = !docLTR ? leftSide : wrapX(from, dir, "before");
+ topRight = !docLTR && openStart && first ? rightSide : fromPos.right;
+ botLeft = !docLTR && openEnd && last ? leftSide : toPos.left;
+ botRight = !docLTR ? rightSide : wrapX(to, dir, "after");
+ }
+ add(topLeft, fromPos.top, topRight - topLeft, fromPos.bottom);
+ if (fromPos.bottom < toPos.top) { add(leftSide, fromPos.bottom, null, toPos.top); }
+ add(botLeft, toPos.top, botRight - botLeft, toPos.bottom);
+ }
+
+ if (!start || cmpCoords(fromPos, start) < 0) { start = fromPos; }
+ if (cmpCoords(toPos, start) < 0) { start = toPos; }
+ if (!end || cmpCoords(fromPos, end) < 0) { end = fromPos; }
+ if (cmpCoords(toPos, end) < 0) { end = toPos; }
+ });
+ 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 () {
+ if (!cm.hasFocus()) { onBlur(cm); }
+ display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden";
+ }, cm.options.cursorBlinkRate); }
+ else if (cm.options.cursorBlinkRate < 0)
+ { display.cursorDiv.style.visibility = "hidden"; }
+ }
+
+ function ensureFocus(cm) {
+ if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); }
+ }
+
+ function delayBlurEvent(cm) {
+ cm.state.delayingBlurEvent = true;
+ setTimeout(function () { if (cm.state.delayingBlurEvent) {
+ cm.state.delayingBlurEvent = false;
+ onBlur(cm);
+ } }, 100);
+ }
+
+ function onFocus(cm, e) {
+ if (cm.state.delayingBlurEvent) { cm.state.delayingBlurEvent = false; }
+
+ if (cm.options.readOnly == "nocursor") { return }
+ if (!cm.state.focused) {
+ signal(cm, "focus", cm, e);
+ cm.state.focused = true;
+ addClass(cm.display.wrapper, "CodeMirror-focused");
+ // This test prevents this from firing when a context
+ // menu is closed (since the input reset would kill the
+ // select-all detection hack)
+ if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) {
+ cm.display.input.reset();
+ if (webkit) { setTimeout(function () { return cm.display.input.reset(true); }, 20); } // Issue #1730
+ }
+ cm.display.input.receivedFocus();
+ }
+ restartBlink(cm);
+ }
+ function onBlur(cm, e) {
+ if (cm.state.delayingBlurEvent) { return }
+
+ if (cm.state.focused) {
+ signal(cm, "blur", cm, e);
+ cm.state.focused = false;
+ rmClass(cm.display.wrapper, "CodeMirror-focused");
+ }
+ clearInterval(cm.display.blinker);
+ setTimeout(function () { if (!cm.state.focused) { cm.display.shift = false; } }, 150);
+ }
+
+ // 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], wrapping = cm.options.lineWrapping;
+ var height = (void 0), width = 0;
+ if (cur.hidden) { continue }
+ if (ie && ie_version < 8) {
+ var bot = cur.node.offsetTop + cur.node.offsetHeight;
+ height = bot - prevBottom;
+ prevBottom = bot;
+ } else {
+ var box = cur.node.getBoundingClientRect();
+ height = box.bottom - box.top;
+ // Check that lines don't extend past the right of the current
+ // editor width
+ if (!wrapping && cur.text.firstChild)
+ { width = cur.text.firstChild.getBoundingClientRect().right - box.left - 1; }
+ }
+ var diff = cur.line.height - height;
+ if (diff > .005 || diff < -.005) {
+ updateLineHeight(cur.line, height);
+ updateWidgetHeight(cur.line);
+ if (cur.rest) { for (var j = 0; j < cur.rest.length; j++)
+ { updateWidgetHeight(cur.rest[j]); } }
+ }
+ if (width > cm.display.sizerWidth) {
+ var chWidth = Math.ceil(width / charWidth(cm.display));
+ if (chWidth > cm.display.maxLineLength) {
+ cm.display.maxLineLength = chWidth;
+ cm.display.maxLine = cur.line;
+ cm.display.maxLineChanged = true;
+ }
+ }
+ }
+ }
+
+ // 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) {
+ var w = line.widgets[i], parent = w.node.parentNode;
+ if (parent) { w.height = parent.offsetHeight; }
+ } }
+ }
+
+ // 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 ? Math.max(0, 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) {
+ from = ensureFrom;
+ to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight);
+ } else if (Math.min(ensureTo, doc.lastLine()) >= to) {
+ from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight);
+ to = ensureTo;
+ }
+ }
+ return {from: from, to: Math.max(to, from + 1)}
+ }
+
+ // 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, rect) {
+ if (signalDOMEvent(cm, "scrollCursorIntoView")) { return }
+
+ var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null;
+ if (rect.top + box.top < 0) { doScroll = true; }
+ else if (rect.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) { doScroll = false; }
+ if (doScroll != null && !phantom) {
+ var scrollNode = elt("div", "\u200b", null, ("position: absolute;\n top: " + (rect.top - display.viewOffset - paddingTop(cm.display)) + "px;\n height: " + (rect.bottom - rect.top + scrollGap(cm) + display.barHeight) + "px;\n left: " + (rect.left) + "px; width: " + (Math.max(2, rect.right - rect.left)) + "px;"));
+ 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; }
+ var rect;
+ if (!cm.options.lineWrapping && pos == end) {
+ // Set pos and end to the cursor positions around the character pos sticks to
+ // If pos.sticky == "before", that is around pos.ch - 1, otherwise around pos.ch
+ // If pos == Pos(_, 0, "before"), pos and end are unchanged
+ pos = pos.ch ? Pos(pos.line, pos.sticky == "before" ? pos.ch - 1 : pos.ch, "after") : pos;
+ end = pos.sticky == "before" ? Pos(pos.line, pos.ch + 1, "before") : pos;
+ }
+ for (var limit = 0; limit < 5; limit++) {
+ var changed = false;
+ var coords = cursorCoords(cm, pos);
+ var endCoords = !end || end == pos ? coords : cursorCoords(cm, end);
+ rect = {left: Math.min(coords.left, endCoords.left),
+ top: Math.min(coords.top, endCoords.top) - margin,
+ right: Math.max(coords.left, endCoords.left),
+ bottom: Math.max(coords.bottom, endCoords.bottom) + margin};
+ var scrollPos = calculateScrollPos(cm, rect);
+ var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft;
+ if (scrollPos.scrollTop != null) {
+ updateScrollTop(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) { break }
+ }
+ return rect
+ }
+
+ // Scroll a given set of coordinates into view (immediately).
+ function scrollIntoView(cm, rect) {
+ var scrollPos = calculateScrollPos(cm, rect);
+ if (scrollPos.scrollTop != null) { updateScrollTop(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, rect) {
+ var display = cm.display, snapMargin = textHeight(cm.display);
+ if (rect.top < 0) { rect.top = 0; }
+ var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop;
+ var screen = displayHeight(cm), result = {};
+ if (rect.bottom - rect.top > screen) { rect.bottom = rect.top + screen; }
+ var docBottom = cm.doc.height + paddingVert(display);
+ var atTop = rect.top < snapMargin, atBottom = rect.bottom > docBottom - snapMargin;
+ if (rect.top < screentop) {
+ result.scrollTop = atTop ? 0 : rect.top;
+ } else if (rect.bottom > screentop + screen) {
+ var newTop = Math.min(rect.top, (atBottom ? docBottom : rect.bottom) - screen);
+ if (newTop != screentop) { result.scrollTop = newTop; }
+ }
+
+ var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft;
+ var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0);
+ var tooWide = rect.right - rect.left > screenw;
+ if (tooWide) { rect.right = rect.left + screenw; }
+ if (rect.left < 10)
+ { result.scrollLeft = 0; }
+ else if (rect.left < screenleft)
+ { result.scrollLeft = Math.max(0, rect.left - (tooWide ? 0 : 10)); }
+ else if (rect.right > screenw + screenleft - 3)
+ { result.scrollLeft = rect.right + (tooWide ? 0 : 10) - screenw; }
+ return result
+ }
+
+ // Store a relative adjustment to the scroll position in the current
+ // operation (to be applied when the operation finishes).
+ function addToScrollTop(cm, top) {
+ if (top == null) { return }
+ resolveScrollToPos(cm);
+ 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();
+ cm.curOp.scrollToPos = {from: cur, to: cur, margin: cm.options.cursorScrollMargin};
+ }
+
+ function scrollToCoords(cm, x, y) {
+ if (x != null || y != null) { resolveScrollToPos(cm); }
+ if (x != null) { cm.curOp.scrollLeft = x; }
+ if (y != null) { cm.curOp.scrollTop = y; }
+ }
+
+ function scrollToRange(cm, range) {
+ resolveScrollToPos(cm);
+ cm.curOp.scrollToPos = range;
+ }
+
+ // 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);
+ scrollToCoordsRange(cm, from, to, range.margin);
+ }
+ }
+
+ function scrollToCoordsRange(cm, from, to, margin) {
+ var sPos = calculateScrollPos(cm, {
+ left: Math.min(from.left, to.left),
+ top: Math.min(from.top, to.top) - margin,
+ right: Math.max(from.right, to.right),
+ bottom: Math.max(from.bottom, to.bottom) + margin
+ });
+ scrollToCoords(cm, sPos.scrollLeft, sPos.scrollTop);
+ }
+
+ // Sync the scrollable area and scrollbars, ensure the viewport
+ // covers the visible area.
+ function updateScrollTop(cm, val) {
+ if (Math.abs(cm.doc.scrollTop - val) < 2) { return }
+ if (!gecko) { updateDisplaySimple(cm, {top: val}); }
+ setScrollTop(cm, val, true);
+ if (gecko) { updateDisplaySimple(cm); }
+ startWorker(cm, 100);
+ }
+
+ function setScrollTop(cm, val, forceScroll) {
+ val = Math.max(0, Math.min(cm.display.scroller.scrollHeight - cm.display.scroller.clientHeight, val));
+ if (cm.display.scroller.scrollTop == val && !forceScroll) { return }
+ cm.doc.scrollTop = val;
+ cm.display.scrollbars.setScrollTop(val);
+ if (cm.display.scroller.scrollTop != val) { cm.display.scroller.scrollTop = val; }
+ }
+
+ // Sync scroller and scrollbar, ensure the gutter elements are
+ // aligned.
+ function setScrollLeft(cm, val, isScroller, forceScroll) {
+ val = Math.max(0, Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth));
+ if ((isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) && !forceScroll) { return }
+ cm.doc.scrollLeft = val;
+ alignHorizontally(cm);
+ if (cm.display.scroller.scrollLeft != val) { cm.display.scroller.scrollLeft = val; }
+ cm.display.scrollbars.setScrollLeft(val);
+ }
+
+ // SCROLLBARS
+
+ // Prepare DOM reads needed to update the scrollbars. Done in one
+ // shot to minimize update/measure roundtrips.
+ function measureForScrollbars(cm) {
+ var d = cm.display, gutterW = d.gutters.offsetWidth;
+ var docH = Math.round(cm.doc.height + paddingVert(cm.display));
+ return {
+ clientHeight: d.scroller.clientHeight,
+ viewHeight: d.wrapper.clientHeight,
+ scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth,
+ viewWidth: d.wrapper.clientWidth,
+ barLeft: cm.options.fixedGutter ? gutterW : 0,
+ docHeight: docH,
+ scrollHeight: docH + scrollGap(cm) + d.barHeight,
+ nativeBarWidth: d.nativeBarWidth,
+ gutterWidth: gutterW
+ }
+ }
+
+ var NativeScrollbars = function(place, scroll, cm) {
+ this.cm = cm;
+ var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar");
+ var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar");
+ vert.tabIndex = horiz.tabIndex = -1;
+ place(vert); place(horiz);
+
+ on(vert, "scroll", function () {
+ if (vert.clientHeight) { scroll(vert.scrollTop, "vertical"); }
+ });
+ on(horiz, "scroll", function () {
+ if (horiz.clientWidth) { scroll(horiz.scrollLeft, "horizontal"); }
+ });
+
+ this.checkedZeroWidth = false;
+ // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8).
+ if (ie && ie_version < 8) { this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; }
+ };
+
+ NativeScrollbars.prototype.update = function (measure) {
+ var needsH = measure.scrollWidth > measure.clientWidth + 1;
+ var needsV = measure.scrollHeight > measure.clientHeight + 1;
+ var sWidth = measure.nativeBarWidth;
+
+ if (needsV) {
+ this.vert.style.display = "block";
+ this.vert.style.bottom = needsH ? sWidth + "px" : "0";
+ var totalHeight = measure.viewHeight - (needsH ? sWidth : 0);
+ // A bug in IE8 can cause this value to be negative, so guard it.
+ this.vert.firstChild.style.height =
+ Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px";
+ } else {
+ this.vert.style.display = "";
+ this.vert.firstChild.style.height = "0";
+ }
+
+ if (needsH) {
+ this.horiz.style.display = "block";
+ this.horiz.style.right = needsV ? sWidth + "px" : "0";
+ this.horiz.style.left = measure.barLeft + "px";
+ var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0);
+ this.horiz.firstChild.style.width =
+ Math.max(0, measure.scrollWidth - measure.clientWidth + totalWidth) + "px";
+ } else {
+ this.horiz.style.display = "";
+ this.horiz.firstChild.style.width = "0";
+ }
+
+ if (!this.checkedZeroWidth && measure.clientHeight > 0) {
+ if (sWidth == 0) { this.zeroWidthHack(); }
+ this.checkedZeroWidth = true;
+ }
+
+ return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}
+ };
+
+ NativeScrollbars.prototype.setScrollLeft = function (pos) {
+ if (this.horiz.scrollLeft != pos) { this.horiz.scrollLeft = pos; }
+ if (this.disableHoriz) { this.enableZeroWidthBar(this.horiz, this.disableHoriz, "horiz"); }
+ };
+
+ NativeScrollbars.prototype.setScrollTop = function (pos) {
+ if (this.vert.scrollTop != pos) { this.vert.scrollTop = pos; }
+ if (this.disableVert) { this.enableZeroWidthBar(this.vert, this.disableVert, "vert"); }
+ };
+
+ NativeScrollbars.prototype.zeroWidthHack = function () {
+ var w = mac && !mac_geMountainLion ? "12px" : "18px";
+ this.horiz.style.height = this.vert.style.width = w;
+ this.horiz.style.pointerEvents = this.vert.style.pointerEvents = "none";
+ this.disableHoriz = new Delayed;
+ this.disableVert = new Delayed;
+ };
+
+ NativeScrollbars.prototype.enableZeroWidthBar = function (bar, delay, type) {
+ bar.style.pointerEvents = "auto";
+ function maybeDisable() {
+ // To find out whether the scrollbar is still visible, we
+ // check whether the element under the pixel in the bottom
+ // right corner of the scrollbar box is the scrollbar box
+ // itself (when the bar is still visible) or its filler child
+ // (when the bar is hidden). If it is still visible, we keep
+ // it enabled, if it's hidden, we disable pointer events.
+ var box = bar.getBoundingClientRect();
+ var elt = type == "vert" ? document.elementFromPoint(box.right - 1, (box.top + box.bottom) / 2)
+ : document.elementFromPoint((box.right + box.left) / 2, box.bottom - 1);
+ if (elt != bar) { bar.style.pointerEvents = "none"; }
+ else { delay.set(1000, maybeDisable); }
+ }
+ delay.set(1000, maybeDisable);
+ };
+
+ NativeScrollbars.prototype.clear = function () {
+ var parent = this.horiz.parentNode;
+ parent.removeChild(this.horiz);
+ parent.removeChild(this.vert);
+ };
+
+ var NullScrollbars = function () {};
+
+ NullScrollbars.prototype.update = function () { return {bottom: 0, right: 0} };
+ NullScrollbars.prototype.setScrollLeft = function () {};
+ NullScrollbars.prototype.setScrollTop = function () {};
+ NullScrollbars.prototype.clear = function () {};
+
+ function updateScrollbars(cm, measure) {
+ if (!measure) { measure = measureForScrollbars(cm); }
+ var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight;
+ updateScrollbarsInner(cm, measure);
+ for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) {
+ if (startWidth != cm.display.barWidth && cm.options.lineWrapping)
+ { updateHeightsInViewport(cm); }
+ updateScrollbarsInner(cm, measureForScrollbars(cm));
+ startWidth = cm.display.barWidth; startHeight = cm.display.barHeight;
+ }
+ }
+
+ // Re-synchronize the fake scrollbars with the actual size of the
+ // content.
+ function updateScrollbarsInner(cm, measure) {
+ var d = cm.display;
+ var sizes = d.scrollbars.update(measure);
+
+ d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px";
+ d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px";
+ d.heightForcer.style.borderBottom = sizes.bottom + "px solid transparent";
+
+ if (sizes.right && sizes.bottom) {
+ d.scrollbarFiller.style.display = "block";
+ d.scrollbarFiller.style.height = sizes.bottom + "px";
+ d.scrollbarFiller.style.width = sizes.right + "px";
+ } else { d.scrollbarFiller.style.display = ""; }
+ if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) {
+ d.gutterFiller.style.display = "block";
+ d.gutterFiller.style.height = sizes.bottom + "px";
+ d.gutterFiller.style.width = measure.gutterWidth + "px";
+ } else { d.gutterFiller.style.display = ""; }
+ }
+
+ var scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars};
+
+ function initScrollbars(cm) {
+ if (cm.display.scrollbars) {
+ cm.display.scrollbars.clear();
+ if (cm.display.scrollbars.addClass)
+ { rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
+ }
+
+ cm.display.scrollbars = new scrollbarModel[cm.options.scrollbarStyle](function (node) {
+ cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller);
+ // Prevent clicks in the scrollbars from killing focus
+ on(node, "mousedown", function () {
+ if (cm.state.focused) { setTimeout(function () { return cm.display.input.focus(); }, 0); }
+ });
+ node.setAttribute("cm-not-content", "true");
+ }, function (pos, axis) {
+ if (axis == "horizontal") { setScrollLeft(cm, pos); }
+ else { updateScrollTop(cm, pos); }
+ }, cm);
+ if (cm.display.scrollbars.addClass)
+ { addClass(cm.display.wrapper, cm.display.scrollbars.addClass); }
+ }
+
+ // 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 = {
+ cm: cm,
+ 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: 0, // 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
+ cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on
+ cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already
+ 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
+ focus: false,
+ id: ++nextOpId // Unique ID
+ };
+ pushOperation(cm.curOp);
+ }
+
+ // Finish an operation, updating the display and signalling delayed events
+ function endOperation(cm) {
+ var op = cm.curOp;
+ if (op) { finishOperation(op, function (group) {
+ for (var i = 0; i < group.ops.length; i++)
+ { group.ops[i].cm.curOp = null; }
+ endOperations(group);
+ }); }
+ }
+
+ // The DOM updates done when an operation finishes are batched so
+ // that the minimum number of relayouts are required.
+ function endOperations(group) {
+ var ops = group.ops;
+ for (var i = 0; i < ops.length; i++) // Read DOM
+ { endOperation_R1(ops[i]); }
+ for (var i$1 = 0; i$1 < ops.length; i$1++) // Write DOM (maybe)
+ { endOperation_W1(ops[i$1]); }
+ for (var i$2 = 0; i$2 < ops.length; i$2++) // Read DOM
+ { endOperation_R2(ops[i$2]); }
+ for (var i$3 = 0; i$3 < ops.length; i$3++) // Write DOM (maybe)
+ { endOperation_W2(ops[i$3]); }
+ for (var i$4 = 0; i$4 < ops.length; i$4++) // Read DOM
+ { endOperation_finish(ops[i$4]); }
+ }
+
+ function endOperation_R1(op) {
+ var cm = op.cm, display = cm.display;
+ maybeClipScrollbars(cm);
+ if (op.updateMaxLine) { findMaxLine(cm); }
+
+ op.mustUpdate = 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;
+ op.update = op.mustUpdate &&
+ new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate);
+ }
+
+ function endOperation_W1(op) {
+ op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update);
+ }
+
+ function endOperation_R2(op) {
+ var cm = op.cm, display = cm.display;
+ if (op.updatedDisplay) { updateHeightsInViewport(cm); }
+
+ op.barMeasure = measureForScrollbars(cm);
+
+ // If the max line changed since it was last measured, measure it,
+ // and ensure the document's width matches it.
+ // updateDisplay_W2 will use these properties to do the actual resizing
+ if (display.maxLineChanged && !cm.options.lineWrapping) {
+ op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3;
+ cm.display.sizerWidth = op.adjustWidthTo;
+ op.barMeasure.scrollWidth =
+ Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth);
+ op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm));
+ }
+
+ if (op.updatedDisplay || op.selectionChanged)
+ { op.preparedSelection = display.input.prepareSelection(); }
+ }
+
+ function endOperation_W2(op) {
+ var cm = op.cm;
+
+ if (op.adjustWidthTo != null) {
+ cm.display.sizer.style.minWidth = op.adjustWidthTo + "px";
+ if (op.maxScrollLeft < cm.doc.scrollLeft)
+ { setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); }
+ cm.display.maxLineChanged = false;
+ }
+
+ var takeFocus = op.focus && op.focus == activeElt();
+ if (op.preparedSelection)
+ { cm.display.input.showSelection(op.preparedSelection, takeFocus); }
+ if (op.updatedDisplay || op.startHeight != cm.doc.height)
+ { updateScrollbars(cm, op.barMeasure); }
+ if (op.updatedDisplay)
+ { setDocumentHeight(cm, op.barMeasure); }
+
+ if (op.selectionChanged) { restartBlink(cm); }
+
+ if (cm.state.focused && op.updateInput)
+ { cm.display.input.reset(op.typing); }
+ if (takeFocus) { ensureFocus(op.cm); }
+ }
+
+ function endOperation_finish(op) {
+ var cm = op.cm, display = cm.display, doc = cm.doc;
+
+ if (op.updatedDisplay) { postUpdateDisplay(cm, op.update); }
+
+ // Abort mouse wheel delta measurement, when scrolling explicitly
+ if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos))
+ { display.wheelStartX = display.wheelStartY = null; }
+
+ // Propagate the scroll position to the actual DOM scroller
+ if (op.scrollTop != null) { setScrollTop(cm, op.scrollTop, op.forceScroll); }
+
+ if (op.scrollLeft != null) { setScrollLeft(cm, op.scrollLeft, true, true); }
+ // If we need to scroll a specific position into view, do so.
+ if (op.scrollToPos) {
+ var rect = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from),
+ clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin);
+ maybeScrollWindow(cm, rect);
+ }
+
+ // 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$1 = 0; i$1 < unhidden.length; ++i$1)
+ { if (unhidden[i$1].lines.length) { signal(unhidden[i$1], "unhide"); } } }
+
+ if (display.wrapper.offsetHeight)
+ { doc.scrollTop = cm.display.scroller.scrollTop; }
+
+ // Fire change events, and delayed event handlers
+ if (op.changeObjs)
+ { signal(cm, "changes", cm, op.changeObjs); }
+ if (op.update)
+ { op.update.finish(); }
+ }
+
+ // 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); }
+ }
+ }
+
+ // HIGHLIGHT WORKER
+
+ function startWorker(cm, time) {
+ if (cm.doc.highlightFrontier < cm.display.viewTo)
+ { cm.state.highlight.set(time, bind(highlightWorker, cm)); }
+ }
+
+ function highlightWorker(cm) {
+ var doc = cm.doc;
+ if (doc.highlightFrontier >= cm.display.viewTo) { return }
+ var end = +new Date + cm.options.workTime;
+ var context = getContextBefore(cm, doc.highlightFrontier);
+ var changedLines = [];
+
+ doc.iter(context.line, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) {
+ if (context.line >= cm.display.viewFrom) { // Visible
+ var oldStyles = line.styles;
+ var resetState = line.text.length > cm.options.maxHighlightLength ? copyState(doc.mode, context.state) : null;
+ var highlighted = highlightLine(cm, line, context, true);
+ if (resetState) { context.state = resetState; }
+ line.styles = highlighted.styles;
+ var oldCls = line.styleClasses, newCls = highlighted.classes;
+ if (newCls) { line.styleClasses = newCls; }
+ else if (oldCls) { line.styleClasses = null; }
+ var ischange = !oldStyles || oldStyles.length != line.styles.length ||
+ oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass);
+ for (var i = 0; !ischange && i < oldStyles.length; ++i) { ischange = oldStyles[i] != line.styles[i]; }
+ if (ischange) { changedLines.push(context.line); }
+ line.stateAfter = context.save();
+ context.nextLine();
+ } else {
+ if (line.text.length <= cm.options.maxHighlightLength)
+ { processLine(cm, line.text, context); }
+ line.stateAfter = context.line % 5 == 0 ? context.save() : null;
+ context.nextLine();
+ }
+ if (+new Date > end) {
+ startWorker(cm, cm.options.workDelay);
+ return true
+ }
+ });
+ doc.highlightFrontier = context.line;
+ doc.modeFrontier = Math.max(doc.modeFrontier, context.line);
+ if (changedLines.length) { runInOp(cm, function () {
+ for (var i = 0; i < changedLines.length; i++)
+ { regLineChange(cm, changedLines[i], "text"); }
+ }); }
+ }
+
+ // DISPLAY DRAWING
+
+ var DisplayUpdate = function(cm, viewport, force) {
+ var display = cm.display;
+
+ this.viewport = viewport;
+ // Store some values that we'll need later (but don't want to force a relayout for)
+ this.visible = visibleLines(display, cm.doc, viewport);
+ this.editorIsHidden = !display.wrapper.offsetWidth;
+ this.wrapperHeight = display.wrapper.clientHeight;
+ this.wrapperWidth = display.wrapper.clientWidth;
+ this.oldDisplayWidth = displayWidth(cm);
+ this.force = force;
+ this.dims = getDimensions(cm);
+ this.events = [];
+ };
+
+ DisplayUpdate.prototype.signal = function (emitter, type) {
+ if (hasHandler(emitter, type))
+ { this.events.push(arguments); }
+ };
+ DisplayUpdate.prototype.finish = function () {
+ for (var i = 0; i < this.events.length; i++)
+ { signal.apply(null, this.events[i]); }
+ };
+
+ function maybeClipScrollbars(cm) {
+ var display = cm.display;
+ if (!display.scrollbarsClipped && display.scroller.offsetWidth) {
+ display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth;
+ display.heightForcer.style.height = scrollGap(cm) + "px";
+ display.sizer.style.marginBottom = -display.nativeBarWidth + "px";
+ display.sizer.style.borderRightWidth = scrollGap(cm) + "px";
+ display.scrollbarsClipped = true;
+ }
+ }
+
+ function selectionSnapshot(cm) {
+ if (cm.hasFocus()) { return null }
+ var active = activeElt();
+ if (!active || !contains(cm.display.lineDiv, active)) { return null }
+ var result = {activeElt: active};
+ if (window.getSelection) {
+ var sel = window.getSelection();
+ if (sel.anchorNode && sel.extend && contains(cm.display.lineDiv, sel.anchorNode)) {
+ result.anchorNode = sel.anchorNode;
+ result.anchorOffset = sel.anchorOffset;
+ result.focusNode = sel.focusNode;
+ result.focusOffset = sel.focusOffset;
+ }
+ }
+ return result
+ }
+
+ function restoreSelection(snapshot) {
+ if (!snapshot || !snapshot.activeElt || snapshot.activeElt == activeElt()) { return }
+ snapshot.activeElt.focus();
+ if (!/^(INPUT|TEXTAREA)$/.test(snapshot.activeElt.nodeName) &&
+ snapshot.anchorNode && contains(document.body, snapshot.anchorNode) && contains(document.body, snapshot.focusNode)) {
+ var sel = window.getSelection(), range = document.createRange();
+ range.setEnd(snapshot.anchorNode, snapshot.anchorOffset);
+ range.collapse(false);
+ sel.removeAllRanges();
+ sel.addRange(range);
+ sel.extend(snapshot.focusNode, snapshot.focusOffset);
+ }
+ }
+
+ // Does the actual updating of the line display. Bails out
+ // (returning false) when there is nothing to be done and forced is
+ // false.
+ function updateDisplayIfNeeded(cm, update) {
+ var display = cm.display, doc = cm.doc;
+
+ if (update.editorIsHidden) {
+ resetView(cm);
+ return false
+ }
+
+ // Bail out if the visible area is already rendered and nothing changed.
+ if (!update.force &&
+ update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo &&
+ (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) &&
+ display.renderedView == display.view && countDirtyView(cm) == 0)
+ { return false }
+
+ if (maybeUpdateLineNumberWidth(cm)) {
+ resetView(cm);
+ update.dims = getDimensions(cm);
+ }
+
+ // Compute a suitable new viewport (from & to)
+ var end = doc.first + doc.size;
+ var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first);
+ var to = Math.min(end, update.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.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth;
+ 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 && !update.force && display.renderedView == display.view &&
+ (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo))
+ { return false }
+
+ // For big changes, we hide the enclosing element during the
+ // update, since that speeds up the operations on most browsers.
+ var selSnapshot = selectionSnapshot(cm);
+ if (toUpdate > 4) { display.lineDiv.style.display = "none"; }
+ patchDisplay(cm, display.updateLineNumbers, update.dims);
+ if (toUpdate > 4) { display.lineDiv.style.display = ""; }
+ display.renderedView = display.view;
+ // There might have been a widget with a focused element that got
+ // hidden or updated, if so re-focus it.
+ restoreSelection(selSnapshot);
+
+ // Prevent selection and cursors from interfering with the scroll
+ // width and height.
+ removeChildren(display.cursorDiv);
+ removeChildren(display.selectionDiv);
+ display.gutters.style.height = display.sizer.style.minHeight = 0;
+
+ if (different) {
+ display.lastWrapHeight = update.wrapperHeight;
+ display.lastWrapWidth = update.wrapperWidth;
+ startWorker(cm, 400);
+ }
+
+ display.updateLineNumbers = null;
+
+ return true
+ }
+
+ function postUpdateDisplay(cm, update) {
+ var viewport = update.viewport;
+
+ for (var first = true;; first = false) {
+ if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) {
+ // Clip forced viewport to actual scrollable area.
+ if (viewport && viewport.top != null)
+ { viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; }
+ // Updated line heights might result in the drawn area not
+ // actually covering the viewport. Keep looping until it does.
+ update.visible = visibleLines(cm.display, cm.doc, viewport);
+ if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo)
+ { break }
+ } else if (first) {
+ update.visible = visibleLines(cm.display, cm.doc, viewport);
+ }
+ if (!updateDisplayIfNeeded(cm, update)) { break }
+ updateHeightsInViewport(cm);
+ var barMeasure = measureForScrollbars(cm);
+ updateSelection(cm);
+ updateScrollbars(cm, barMeasure);
+ setDocumentHeight(cm, barMeasure);
+ update.force = false;
+ }
+
+ update.signal(cm, "update", cm);
+ if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) {
+ update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo);
+ cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo;
+ }
+ }
+
+ function updateDisplaySimple(cm, viewport) {
+ var update = new DisplayUpdate(cm, viewport);
+ if (updateDisplayIfNeeded(cm, update)) {
+ updateHeightsInViewport(cm);
+ postUpdateDisplay(cm, update);
+ var barMeasure = measureForScrollbars(cm);
+ updateSelection(cm);
+ updateScrollbars(cm, barMeasure);
+ setDocumentHeight(cm, barMeasure);
+ update.finish();
+ }
+ }
+
+ // 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 || lineView.node.parentNode != container) { // 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); }
+ }
+
+ function updateGutterSpace(display) {
+ var width = display.gutters.offsetWidth;
+ display.sizer.style.marginLeft = width + "px";
+ }
+
+ function setDocumentHeight(cm, measure) {
+ cm.display.sizer.style.minHeight = measure.docHeight + "px";
+ cm.display.heightForcer.style.top = measure.docHeight + "px";
+ cm.display.gutters.style.height = (measure.docHeight + cm.display.barHeight + scrollGap(cm)) + "px";
+ }
+
+ // 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) {
+ if (view[i].gutter)
+ { view[i].gutter.style.left = left; }
+ if (view[i].gutterBackground)
+ { view[i].gutterBackground.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) + 1;
+ display.lineNumWidth = display.lineNumInnerWidth + padding;
+ display.lineNumChars = display.lineNumInnerWidth ? last.length : -1;
+ display.lineGutter.style.width = display.lineNumWidth + "px";
+ updateGutterSpace(cm.display);
+ return true
+ }
+ return false
+ }
+
+ function getGutters(gutters, lineNumbers) {
+ var result = [], sawLineNumbers = false;
+ for (var i = 0; i < gutters.length; i++) {
+ var name = gutters[i], style = null;
+ if (typeof name != "string") { style = name.style; name = name.className; }
+ if (name == "CodeMirror-linenumbers") {
+ if (!lineNumbers) { continue }
+ else { sawLineNumbers = true; }
+ }
+ result.push({className: name, style: style});
+ }
+ if (lineNumbers && !sawLineNumbers) { result.push({className: "CodeMirror-linenumbers", style: null}); }
+ return result
+ }
+
+ // Rebuild the gutter elements, ensure the margin to the left of the
+ // code matches their width.
+ function renderGutters(display) {
+ var gutters = display.gutters, specs = display.gutterSpecs;
+ removeChildren(gutters);
+ display.lineGutter = null;
+ for (var i = 0; i < specs.length; ++i) {
+ var ref = specs[i];
+ var className = ref.className;
+ var style = ref.style;
+ var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + className));
+ if (style) { gElt.style.cssText = style; }
+ if (className == "CodeMirror-linenumbers") {
+ display.lineGutter = gElt;
+ gElt.style.width = (display.lineNumWidth || 1) + "px";
+ }
+ }
+ gutters.style.display = specs.length ? "" : "none";
+ updateGutterSpace(display);
+ }
+
+ function updateGutters(cm) {
+ renderGutters(cm.display);
+ regChange(cm);
+ alignHorizontally(cm);
+ }
+
+ // 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, input, options) {
+ var d = this;
+ this.input = input;
+
+ // Covers bottom-right square when both scrollbars are present.
+ d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler");
+ d.scrollbarFiller.setAttribute("cm-not-content", "true");
+ // Covers bottom of gutter when coverGutterNextToScrollbar is on
+ // and h scrollbar is present.
+ d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler");
+ d.gutterFiller.setAttribute("cm-not-content", "true");
+ // Will contain the actual code, positioned to cover the viewport.
+ d.lineDiv = eltP("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 = eltP("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv],
+ null, "position: relative; outline: none");
+ var lines = eltP("div", [d.lineSpace], "CodeMirror-lines");
+ // Moved around its parent to cover visible view.
+ d.mover = elt("div", [lines], null, "position: relative");
+ // Set to the height of the document, allowing scrolling.
+ d.sizer = elt("div", [d.mover], "CodeMirror-sizer");
+ d.sizerWidth = null;
+ // 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: " + scrollerGap + "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.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror");
+
+ // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported)
+ if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; }
+ if (!webkit && !(gecko && mobile)) { d.scroller.draggable = true; }
+
+ if (place) {
+ 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;
+ d.reportedViewFrom = d.reportedViewTo = doc.first;
+ // Information about the rendered lines.
+ d.view = [];
+ d.renderedView = null;
+ // 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.lastWrapHeight = d.lastWrapWidth = 0;
+ d.updateLineNumbers = null;
+
+ d.nativeBarWidth = d.barHeight = d.barWidth = 0;
+ d.scrollbarsClipped = false;
+
+ // 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;
+ // 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;
+
+ d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
+
+ // 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;
+
+ // Used to track whether anything happened since the context menu
+ // was opened.
+ d.selForContextMenu = null;
+
+ d.activeTouch = null;
+
+ d.gutterSpecs = getGutters(options.gutters, options.lineNumbers);
+ renderGutters(d);
+
+ input.init(d);
+ }
+
+ // 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 wheelEventDelta(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; }
+ return {x: dx, y: dy}
+ }
+ function wheelEventPixels(e) {
+ var delta = wheelEventDelta(e);
+ delta.x *= wheelPixelsPerUnit;
+ delta.y *= wheelPixelsPerUnit;
+ return delta
+ }
+
+ function onScrollWheel(cm, e) {
+ var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y;
+
+ var display = cm.display, scroll = display.scroller;
+ // Quit if there's nothing to scroll here
+ var canScrollX = scroll.scrollWidth > scroll.clientWidth;
+ var canScrollY = scroll.scrollHeight > scroll.clientHeight;
+ if (!(dx && canScrollX || dy && canScrollY)) { 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 && canScrollY)
+ { updateScrollTop(cm, Math.max(0, scroll.scrollTop + dy * wheelPixelsPerUnit)); }
+ setScrollLeft(cm, Math.max(0, scroll.scrollLeft + dx * wheelPixelsPerUnit));
+ // Only prevent default scrolling if vertical scrolling is
+ // actually possible. Otherwise, it causes vertical scroll
+ // jitter on OSX trackpads when deltaX is small and deltaY
+ // is large (issue #3579)
+ if (!dy || (dy && canScrollY))
+ { 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); }
+ updateDisplaySimple(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;
+ }
+ }
+ }
+
+ // 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).
+ var Selection = function(ranges, primIndex) {
+ this.ranges = ranges;
+ this.primIndex = primIndex;
+ };
+
+ Selection.prototype.primary = function () { return this.ranges[this.primIndex] };
+
+ Selection.prototype.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 (!equalCursorPos(here.anchor, there.anchor) || !equalCursorPos(here.head, there.head)) { return false }
+ }
+ return true
+ };
+
+ Selection.prototype.deepCopy = function () {
+ var out = [];
+ for (var 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)
+ };
+
+ Selection.prototype.somethingSelected = function () {
+ for (var i = 0; i < this.ranges.length; i++)
+ { if (!this.ranges[i].empty()) { return true } }
+ return false
+ };
+
+ Selection.prototype.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
+ };
+
+ var Range = function(anchor, head) {
+ this.anchor = anchor; this.head = head;
+ };
+
+ Range.prototype.from = function () { return minPos(this.anchor, this.head) };
+ Range.prototype.to = function () { return maxPos(this.anchor, this.head) };
+ Range.prototype.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(cm, ranges, primIndex) {
+ var mayTouch = cm && cm.options.selectionsMayTouch;
+ 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];
+ var diff = cmp(prev.to(), cur.from());
+ if (mayTouch && !cur.empty() ? diff > 0 : diff >= 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)
+ }
+
+ // Compute the position of the end of a change (its 'to' property
+ // refers to the pre-change end).
+ function changeEnd(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(doc.cm, 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)
+ }
+
+ // Used to get the editor into a consistent state again when options change.
+
+ function loadMode(cm) {
+ cm.doc.mode = 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.modeFrontier = cm.doc.highlightFrontier = cm.doc.first;
+ startWorker(cm, 100);
+ cm.state.modeGen++;
+ if (cm.curOp) { regChange(cm); }
+ }
+
+ // 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);
+ }
+ function linesFor(start, end) {
+ var result = [];
+ for (var i = start; i < end; ++i)
+ { result.push(new Line(text[i], spansFor(i), estimateHeight)); }
+ return result
+ }
+
+ 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 (change.full) {
+ doc.insert(0, linesFor(0, text.length));
+ doc.remove(text.length, doc.size - text.length);
+ } else if (isWholeLineUpdate(doc, change)) {
+ // This is a whole-line replace. Treated specially to make
+ // sure line objects move the way they are supposed to.
+ var added = linesFor(0, text.length - 1);
+ 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 {
+ var added$1 = linesFor(1, text.length - 1);
+ added$1.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$1);
+ }
+ } 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);
+ var added$2 = linesFor(1, text.length - 1);
+ if (nlines > 1) { doc.remove(from.line + 1, nlines - 1); }
+ doc.insert(from.line + 1, added$2);
+ }
+
+ signalLater(doc, "change", doc, change);
+ }
+
+ // 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);
+ setDirectionClass(cm);
+ if (!cm.options.lineWrapping) { findMaxLine(cm); }
+ cm.options.mode = doc.modeOption;
+ regChange(cm);
+ }
+
+ function setDirectionClass(cm) {
+ (cm.doc.direction == "rtl" ? addClass : rmClass)(cm.display.lineDiv, "CodeMirror-rtl");
+ }
+
+ function directionChanged(cm) {
+ runInOp(cm, function () {
+ setDirectionClass(cm);
+ regChange(cm);
+ });
+ }
+
+ 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 = this.lastSelOp = 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) { return 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, or 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;
+ var last;
+
+ if ((hist.lastOp == opId ||
+ hist.lastOrigin == change.origin && change.origin &&
+ ((change.origin.charAt(0) == "+" && hist.lastModTime > time - (doc.cm ? doc.cm.options.historyEventDelay : 500)) ||
+ change.origin.charAt(0) == "*")) &&
+ (cur = lastChangeEvent(hist, hist.lastOp == opId))) {
+ // Merge this change into the last event
+ 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 = hist.lastSelOp = 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.lastSelOp ||
+ (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.lastSelOp = 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 }
+ var out;
+ for (var i = 0; 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 }
+ var nw = [];
+ for (var i = 0; i < change.text.length; ++i)
+ { nw.push(removeClearedSpans(found[i])); }
+ return nw
+ }
+
+ // 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 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) {
+ var copy = [];
+ for (var i = 0; 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 = (void 0);
+ 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
+ }
+
+ // 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(range, head, other, extend) {
+ if (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, extend) {
+ if (extend == null) { extend = doc.cm && (doc.cm.display.shift || doc.extend); }
+ setSelection(doc, new Selection([extendRange(doc.sel.primary(), head, other, extend)], 0), options);
+ }
+
+ // Extend all selections (pos is an array of selections with length
+ // equal the number of selections)
+ function extendSelections(doc, heads, options) {
+ var out = [];
+ var extend = doc.cm && (doc.cm.display.shift || doc.extend);
+ for (var i = 0; i < doc.sel.ranges.length; i++)
+ { out[i] = extendRange(doc.sel.ranges[i], heads[i], null, extend); }
+ var newSel = normalizeSelection(doc.cm, 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(doc.cm, 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, options) {
+ 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)); }
+ },
+ origin: options && options.origin
+ };
+ signal(doc, "beforeSelectionChange", doc, obj);
+ if (doc.cm) { signal(doc.cm, "beforeSelectionChange", doc.cm, obj); }
+ if (obj.ranges != sel.ranges) { return normalizeSelection(doc.cm, 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, options); }
+
+ var bias = options && options.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 = 1;
+ doc.cm.curOp.selectionChanged = true;
+ signalCursorActivity(doc.cm);
+ }
+ 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));
+ }
+
+ // 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 old = sel.ranges.length == doc.sel.ranges.length && doc.sel.ranges[i];
+ var newAnchor = skipAtomic(doc, range.anchor, old && old.anchor, bias, mayClear);
+ var newHead = skipAtomic(doc, range.head, old && old.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(doc.cm, out, sel.primIndex) : sel
+ }
+
+ function skipAtomicInner(doc, pos, oldPos, dir, mayClear) {
+ var line = getLine(doc, pos.line);
+ if (line.markedSpans) { for (var i = 0; i < line.markedSpans.length; ++i) {
+ var sp = line.markedSpans[i], m = sp.marker;
+
+ // Determine if we should prevent the cursor being placed to the left/right of an atomic marker
+ // Historically this was determined using the inclusiveLeft/Right option, but the new way to control it
+ // is with selectLeft/Right
+ var preventCursorLeft = ("selectLeft" in m) ? !m.selectLeft : m.inclusiveLeft;
+ var preventCursorRight = ("selectRight" in m) ? !m.selectRight : m.inclusiveRight;
+
+ if ((sp.from == null || (preventCursorLeft ? sp.from <= pos.ch : sp.from < pos.ch)) &&
+ (sp.to == null || (preventCursorRight ? sp.to >= pos.ch : sp.to > pos.ch))) {
+ if (mayClear) {
+ signal(m, "beforeCursorEnter");
+ if (m.explicitlyCleared) {
+ if (!line.markedSpans) { break }
+ else {--i; continue}
+ }
+ }
+ if (!m.atomic) { continue }
+
+ if (oldPos) {
+ var near = m.find(dir < 0 ? 1 : -1), diff = (void 0);
+ if (dir < 0 ? preventCursorRight : preventCursorLeft)
+ { near = movePos(doc, near, -dir, near && near.line == pos.line ? line : null); }
+ if (near && near.line == pos.line && (diff = cmp(near, oldPos)) && (dir < 0 ? diff < 0 : diff > 0))
+ { return skipAtomicInner(doc, near, pos, dir, mayClear) }
+ }
+
+ var far = m.find(dir < 0 ? -1 : 1);
+ if (dir < 0 ? preventCursorLeft : preventCursorRight)
+ { far = movePos(doc, far, dir, far.line == pos.line ? line : null); }
+ return far ? skipAtomicInner(doc, far, pos, dir, mayClear) : null
+ }
+ } }
+ return pos
+ }
+
+ // Ensure a given position is not inside an atomic range.
+ function skipAtomic(doc, pos, oldPos, bias, mayClear) {
+ var dir = bias || 1;
+ var found = skipAtomicInner(doc, pos, oldPos, dir, mayClear) ||
+ (!mayClear && skipAtomicInner(doc, pos, oldPos, dir, true)) ||
+ skipAtomicInner(doc, pos, oldPos, -dir, mayClear) ||
+ (!mayClear && skipAtomicInner(doc, pos, oldPos, -dir, true));
+ if (!found) {
+ doc.cantEdit = true;
+ return Pos(doc.first, 0)
+ }
+ return found
+ }
+
+ function movePos(doc, pos, dir, line) {
+ if (dir < 0 && pos.ch == 0) {
+ if (pos.line > doc.first) { return clipPos(doc, Pos(pos.line - 1)) }
+ else { return null }
+ } else if (dir > 0 && pos.ch == (line || getLine(doc, pos.line)).text.length) {
+ if (pos.line < doc.first + doc.size - 1) { return Pos(pos.line + 1, 0) }
+ else { return null }
+ } else {
+ return new Pos(pos.line, pos.ch + dir)
+ }
+ }
+
+ function selectAll(cm) {
+ cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);
+ }
+
+ // UPDATING
+
+ // 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 () { return obj.canceled = true; }
+ };
+ if (update) { obj.update = function (from, to, text, origin) {
+ if (from) { obj.from = clipPos(doc, from); }
+ if (to) { obj.to = clipPos(doc, to); }
+ if (text) { obj.text = text; }
+ if (origin !== undefined) { obj.origin = origin; }
+ }; }
+ signal(doc, "beforeChange", doc, obj);
+ if (doc.cm) { signal(doc.cm, "beforeChange", doc.cm, obj); }
+
+ if (obj.canceled) {
+ if (doc.cm) { doc.cm.curOp.updateInput = 2; }
+ 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, origin: change.origin}); }
+ } 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) {
+ var suppress = doc.cm && doc.cm.state.suppressEdits;
+ if (suppress && !allowSelectionOnly) { 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)
+ var i = 0;
+ for (; 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 if (suppress) {
+ source.push(event);
+ return
+ } 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");
+
+ var loop = function ( 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) : lst(source);
+ makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change));
+ if (!i && doc.cm) { doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); }
+ 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));
+ });
+ };
+
+ for (var i$1 = event.changes.length - 1; i$1 >= 0; --i$1) {
+ var returned = loop( i$1 );
+
+ if ( returned ) return returned.v;
+ }
+ }
+
+ // Sub-views need their line numbers shifted when text is added
+ // above or below them in the parent document.
+ function shiftDoc(doc, distance) {
+ if (distance == 0) { return }
+ 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);
+ for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++)
+ { regLineChange(doc.cm, l, "gutter"); }
+ }
+ }
+
+ // 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); }
+ if (doc.cm) { makeChangeSingleDocInEditor(doc.cm, change, spans); }
+ else { updateDoc(doc, change, spans); }
+ setSelectionNoUndo(doc, selAfter, sel_dontScroll);
+
+ if (doc.cantEdit && skipAtomic(doc, Pos(doc.firstLine(), 0)))
+ { doc.cantEdit = false; }
+ }
+
+ // 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)
+ { signalCursorActivity(cm); }
+
+ 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; }
+ }
+
+ retreatFrontier(doc, 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 (change.full)
+ { regChange(cm); }
+ else 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); }
+
+ var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change");
+ if (changeHandler || changesHandler) {
+ var obj = {
+ from: from, to: to,
+ text: change.text,
+ removed: change.removed,
+ origin: change.origin
+ };
+ if (changeHandler) { signalLater(cm, "change", cm, obj); }
+ if (changesHandler) { (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); }
+ }
+ cm.display.selForContextMenu = null;
+ }
+
+ function replaceRange(doc, code, from, to, origin) {
+ var assign;
+
+ if (!to) { to = from; }
+ if (cmp(to, from) < 0) { (assign = [to, from], from = assign[0], to = assign[1]); }
+ if (typeof code == "string") { code = doc.splitLines(code); }
+ makeChange(doc, {from: from, to: to, text: code, origin: origin});
+ }
+
+ // 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$1 = 0; j$1 < sub.changes.length; ++j$1) {
+ var cur = sub.changes[j$1];
+ 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);
+ }
+
+ // Utility for applying a change to a line by handle or number,
+ // returning the number and optionally registering the line as
+ // changed.
+ function changeLine(doc, handle, changeType, op) {
+ var no = handle, line = handle;
+ if (typeof handle == "number") { line = getLine(doc, clipLine(doc, handle)); }
+ else { no = lineNo(handle); }
+ if (no == null) { return null }
+ if (op(line, no) && doc.cm) { regLineChange(doc.cm, no, changeType); }
+ return line
+ }
+
+ // 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;
+ var height = 0;
+ for (var i = 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) {
+ // To avoid memory thrashing when child.lines is huge (e.g. first view of a large file), it's never spliced.
+ // Instead, small slices are taken. They're taken in order because sequential memory accesses are fastest.
+ var remaining = child.lines.length % 25 + 25;
+ for (var pos = remaining; pos < child.lines.length;) {
+ var leaf = new LeafChunk(child.lines.slice(pos, pos += 25));
+ child.height -= leaf.height;
+ this.children.splice(++i, 0, leaf);
+ leaf.parent = this;
+ }
+ child.lines = child.lines.slice(0, remaining);
+ 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; }
+ }
+ }
+ };
+
+ // Line widgets are block elements displayed above or below a line.
+
+ var LineWidget = function(doc, node, options) {
+ if (options) { for (var opt in options) { if (options.hasOwnProperty(opt))
+ { this[opt] = options[opt]; } } }
+ this.doc = doc;
+ this.node = node;
+ };
+
+ LineWidget.prototype.clear = function () {
+ var cm = this.doc.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);
+ updateLineHeight(line, Math.max(0, line.height - height));
+ if (cm) {
+ runInOp(cm, function () {
+ adjustScrollWhenAboveVisible(cm, line, -height);
+ regLineChange(cm, no, "widget");
+ });
+ signalLater(cm, "lineWidgetCleared", cm, this, no);
+ }
+ };
+
+ LineWidget.prototype.changed = function () {
+ var this$1 = this;
+
+ var oldH = this.height, cm = this.doc.cm, line = this.line;
+ this.height = null;
+ var diff = widgetHeight(this) - oldH;
+ if (!diff) { return }
+ if (!lineIsHidden(this.doc, line)) { updateLineHeight(line, line.height + diff); }
+ if (cm) {
+ runInOp(cm, function () {
+ cm.curOp.forceUpdate = true;
+ adjustScrollWhenAboveVisible(cm, line, diff);
+ signalLater(cm, "lineWidgetChanged", cm, this$1, lineNo(line));
+ });
+ }
+ };
+ eventMixin(LineWidget);
+
+ function adjustScrollWhenAboveVisible(cm, line, diff) {
+ if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop))
+ { addToScrollTop(cm, diff); }
+ }
+
+ function addLineWidget(doc, handle, node, options) {
+ var widget = new LineWidget(doc, node, options);
+ var cm = doc.cm;
+ if (cm && widget.noHScroll) { cm.display.alignWidgets = true; }
+ changeLine(doc, 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 (cm && !lineIsHidden(doc, line)) {
+ var aboveVisible = heightAtLine(line) < doc.scrollTop;
+ updateLineHeight(line, line.height + widgetHeight(widget));
+ if (aboveVisible) { addToScrollTop(cm, widget.height); }
+ cm.curOp.forceUpdate = true;
+ }
+ return true
+ });
+ if (cm) { signalLater(cm, "lineWidgetAdded", cm, widget, typeof handle == "number" ? handle : lineNo(handle)); }
+ return widget
+ }
+
+ // 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.
+
+ // 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;
+
+ var TextMarker = function(doc, type) {
+ this.lines = [];
+ this.type = type;
+ this.doc = doc;
+ this.id = ++nextMarkerId;
+ };
+
+ // 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$1 = 0; i$1 < this.lines.length; ++i$1) {
+ var visual = visualLine(this.lines[i$1]), 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, min, max); }
+ if (withOp) { endOperation(cm); }
+ if (this.parent) { this.parent.clear(); }
+ };
+
+ // 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 this$1 = this;
+
+ 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); }
+ }
+ signalLater(cm, "markerChanged", cm, this$1);
+ });
+ };
+
+ 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);
+ }
+ };
+ eventMixin(TextMarker);
+
+ // 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, false); }
+ // 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 = eltP("span", [marker.replacedWith], "CodeMirror-widget");
+ if (!options.handleMouseEvents) { marker.widgetNode.setAttribute("cm-ignore-events", "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") }
+ seeCollapsedSpans();
+ }
+
+ 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 () { return marker.clear(); }); }
+
+ if (marker.readOnly) {
+ seeReadOnlySpans();
+ 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.startStyle || marker.endStyle || marker.css ||
+ marker.attributes || marker.title)
+ { 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 = function(markers, primary) {
+ this.markers = markers;
+ this.primary = primary;
+ for (var i = 0; i < markers.length; ++i)
+ { markers[i].parent = this; }
+ };
+
+ 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)
+ };
+ eventMixin(SharedTextMarker);
+
+ 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)
+ }
+
+ function findSharedMarkers(doc) {
+ return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), function (m) { return m.parent; })
+ }
+
+ function copySharedMarkers(doc, markers) {
+ for (var i = 0; i < markers.length; i++) {
+ var marker = markers[i], pos = marker.find();
+ var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to);
+ if (cmp(mFrom, mTo)) {
+ var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type);
+ marker.markers.push(subMark);
+ subMark.parent = marker;
+ }
+ }
+ }
+
+ function detachSharedMarkers(markers) {
+ var loop = function ( i ) {
+ var marker = markers[i], linked = [marker.primary.doc];
+ linkedDocs(marker.primary.doc, function (d) { return linked.push(d); });
+ for (var j = 0; j < marker.markers.length; j++) {
+ var subMarker = marker.markers[j];
+ if (indexOf(linked, subMarker.doc) == -1) {
+ subMarker.parent = null;
+ marker.markers.splice(j--, 1);
+ }
+ }
+ };
+
+ for (var i = 0; i < markers.length; i++) loop( i );
+ }
+
+ var nextDocId = 0;
+ var Doc = function(text, mode, firstLine, lineSep, direction) {
+ if (!(this instanceof Doc)) { return new Doc(text, mode, firstLine, lineSep, direction) }
+ 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.modeFrontier = this.highlightFrontier = firstLine;
+ var start = Pos(firstLine, 0);
+ this.sel = simpleSelection(start);
+ this.history = new History(null);
+ this.id = ++nextDocId;
+ this.modeOption = mode;
+ this.lineSep = lineSep;
+ this.direction = (direction == "rtl") ? "rtl" : "ltr";
+ this.extend = false;
+
+ if (typeof text == "string") { text = this.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 || this.lineSeparator())
+ },
+ 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: this.splitLines(code), origin: "setValue", full: true}, true);
+ if (this.cm) { scrollToCoords(this.cm, 0, 0); }
+ setSelection(this, simpleSelection(top), sel_dontScroll);
+ }),
+ 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 || this.lineSeparator())
+ },
+
+ 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) {
+ var heads = map(this.sel.ranges, f);
+ extendSelections(this, clipPosArray(this, heads), options);
+ }),
+ setSelections: docMethodOp(function(ranges, primary, options) {
+ if (!ranges.length) { return }
+ var out = [];
+ for (var i = 0; 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(this.cm, 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(this.cm, 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 || this.lineSeparator()) }
+ },
+ 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 || this.lineSeparator()); }
+ parts[i] = sel;
+ }
+ return parts
+ },
+ replaceSelection: 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: docMethodOp(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: this.splitLines(code[i]), origin: origin};
+ }
+ var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse);
+ for (var i$1 = changes.length - 1; i$1 >= 0; i$1--)
+ { makeChange(this, changes[i$1]); }
+ 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$1 = 0; i$1 < hist.undone.length; i$1++) { if (!hist.undone[i$1].ranges) { ++undone; } }
+ return {undo: done, redo: undone}
+ },
+ clearHistory: function() {
+ var this$1 = this;
+
+ this.history = new History(this.history.maxGeneration);
+ linkedDocs(this, function (doc) { return doc.history = this$1.history; }, true);
+ },
+
+ markClean: function() {
+ this.cleanGeneration = this.changeGeneration(true);
+ },
+ changeGeneration: function(forceSplit) {
+ if (forceSplit)
+ { this.history.lastOp = this.history.lastSelOp = 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);
+ },
+
+ setGutterMarker: docMethodOp(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: docMethodOp(function(gutterID) {
+ var this$1 = this;
+
+ this.iter(function (line) {
+ if (line.gutterMarkers && line.gutterMarkers[gutterID]) {
+ changeLine(this$1, line, "gutter", function () {
+ line.gutterMarkers[gutterID] = null;
+ if (isEmpty(line.gutterMarkers)) { line.gutterMarkers = null; }
+ return true
+ });
+ }
+ });
+ }),
+
+ lineInfo: function(line) {
+ var n;
+ if (typeof line == "number") {
+ if (!isLine(this, line)) { return null }
+ n = line;
+ line = getLine(this, line);
+ if (!line) { return null }
+ } else {
+ 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}
+ },
+
+ addLineClass: docMethodOp(function(handle, where, cls) {
+ return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
+ var prop = where == "text" ? "textClass"
+ : where == "background" ? "bgClass"
+ : where == "gutter" ? "gutterClass" : "wrapClass";
+ if (!line[prop]) { line[prop] = cls; }
+ else if (classTest(cls).test(line[prop])) { return false }
+ else { line[prop] += " " + cls; }
+ return true
+ })
+ }),
+ removeLineClass: docMethodOp(function(handle, where, cls) {
+ return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) {
+ var prop = where == "text" ? "textClass"
+ : where == "background" ? "bgClass"
+ : where == "gutter" ? "gutterClass" : "wrapClass";
+ var cur = line[prop];
+ if (!cur) { return false }
+ else if (cls == null) { line[prop] = null; }
+ else {
+ var found = cur.match(classTest(cls));
+ 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: docMethodOp(function(handle, node, options) {
+ return addLineWidget(this, handle, node, options)
+ }),
+ removeLineWidget: function(widget) { widget.clear(); },
+
+ markText: function(from, to, options) {
+ return markText(this, clipPos(this, from), clipPos(this, to), options, options && options.type || "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,
+ handleMouseEvents: options && options.handleMouseEvents};
+ 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, filter) {
+ 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 (!(span.to != null && lineNo == from.line && from.ch >= span.to ||
+ span.from == null && lineNo != from.line ||
+ span.from != null && lineNo == to.line && span.from >= to.ch) &&
+ (!filter || filter(span.marker)))
+ { 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, sepSize = this.lineSeparator().length;
+ this.iter(function (line) {
+ var sz = line.text.length + sepSize;
+ 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 }
+ var sepSize = this.lineSeparator().length;
+ this.iter(this.first, coords.line, function (line) { // iter aborts when callback returns a truthy value
+ index += line.text.length + sepSize;
+ });
+ return index
+ },
+
+ copy: function(copyHistory) {
+ var doc = new Doc(getLines(this, this.first, this.first + this.size),
+ this.modeOption, this.first, this.lineSep, this.direction);
+ 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, this.lineSep, this.direction);
+ 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}];
+ copySharedMarkers(copy, findSharedMarkers(this));
+ 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);
+ detachSharedMarkers(findSharedMarkers(this));
+ break
+ } }
+ // If the histories were shared, split them again
+ if (other.history == this.history) {
+ var splitIds = [other.id];
+ linkedDocs(other, function (doc) { return 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},
+
+ splitLines: function(str) {
+ if (this.lineSep) { return str.split(this.lineSep) }
+ return splitLinesAuto(str)
+ },
+ lineSeparator: function() { return this.lineSep || "\n" },
+
+ setDirection: docMethodOp(function (dir) {
+ if (dir != "rtl") { dir = "ltr"; }
+ if (dir == this.direction) { return }
+ this.direction = dir;
+ this.iter(function (line) { return line.order = null; });
+ if (this.cm) { directionChanged(this.cm); }
+ })
+ });
+
+ // Public alias.
+ Doc.prototype.eachLine = Doc.prototype.iter;
+
+ // 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;
+ clearDragCursor(cm);
+ if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e))
+ { return }
+ e_preventDefault(e);
+ if (ie) { lastDrop = +new Date; }
+ var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files;
+ if (!pos || cm.isReadOnly()) { 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 markAsReadAndPasteIfAllFilesAreRead = function () {
+ if (++read == n) {
+ operation(cm, function () {
+ pos = clipPos(cm.doc, pos);
+ var change = {from: pos, to: pos,
+ text: cm.doc.splitLines(
+ text.filter(function (t) { return t != null; }).join(cm.doc.lineSeparator())),
+ origin: "paste"};
+ makeChange(cm.doc, change);
+ setSelectionReplaceHistory(cm.doc, simpleSelection(clipPos(cm.doc, pos), clipPos(cm.doc, changeEnd(change))));
+ })();
+ }
+ };
+ var readTextFromFile = function (file, i) {
+ if (cm.options.allowDropFileTypes &&
+ indexOf(cm.options.allowDropFileTypes, file.type) == -1) {
+ markAsReadAndPasteIfAllFilesAreRead();
+ return
+ }
+ var reader = new FileReader;
+ reader.onerror = function () { return markAsReadAndPasteIfAllFilesAreRead(); };
+ reader.onload = function () {
+ var content = reader.result;
+ if (/[\x00-\x08\x0e-\x1f]{2}/.test(content)) {
+ markAsReadAndPasteIfAllFilesAreRead();
+ return
+ }
+ text[i] = content;
+ markAsReadAndPasteIfAllFilesAreRead();
+ };
+ reader.readAsText(file);
+ };
+ for (var i = 0; i < files.length; i++) { readTextFromFile(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(function () { return cm.display.input.focus(); }, 20);
+ return
+ }
+ try {
+ var text$1 = e.dataTransfer.getData("Text");
+ if (text$1) {
+ var selected;
+ if (cm.state.draggingText && !cm.state.draggingText.copy)
+ { selected = cm.listSelections(); }
+ setSelectionNoUndo(cm.doc, simpleSelection(pos, pos));
+ if (selected) { for (var i$1 = 0; i$1 < selected.length; ++i$1)
+ { replaceRange(cm.doc, "", selected[i$1].anchor, selected[i$1].head, "drag"); } }
+ cm.replaceSelection(text$1, "around", "paste");
+ cm.display.input.focus();
+ }
+ }
+ catch(e$1){}
+ }
+ }
+
+ function onDragStart(cm, e) {
+ if (ie && (!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());
+ e.dataTransfer.effectAllowed = "copyMove";
+
+ // 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); }
+ }
+ }
+
+ function onDragOver(cm, e) {
+ var pos = posFromMouse(cm, e);
+ if (!pos) { return }
+ var frag = document.createDocumentFragment();
+ drawSelectionCursor(cm, pos, frag);
+ if (!cm.display.dragCursor) {
+ cm.display.dragCursor = elt("div", null, "CodeMirror-cursors CodeMirror-dragcursors");
+ cm.display.lineSpace.insertBefore(cm.display.dragCursor, cm.display.cursorDiv);
+ }
+ removeChildrenAndAdd(cm.display.dragCursor, frag);
+ }
+
+ function clearDragCursor(cm) {
+ if (cm.display.dragCursor) {
+ cm.display.lineSpace.removeChild(cm.display.dragCursor);
+ cm.display.dragCursor = null;
+ }
+ }
+
+ // These must be handled carefully, because naively registering a
+ // handler for each editor will cause the editors to never be
+ // garbage collected.
+
+ function forEachCodeMirror(f) {
+ if (!document.getElementsByClassName) { return }
+ var byClass = document.getElementsByClassName("CodeMirror"), editors = [];
+ for (var i = 0; i < byClass.length; i++) {
+ var cm = byClass[i].CodeMirror;
+ if (cm) { editors.push(cm); }
+ }
+ if (editors.length) { editors[0].operation(function () {
+ for (var i = 0; i < editors.length; i++) { f(editors[i]); }
+ }); }
+ }
+
+ var globalsRegistered = false;
+ function ensureGlobalHandlers() {
+ if (globalsRegistered) { return }
+ registerGlobalHandlers();
+ globalsRegistered = true;
+ }
+ function registerGlobalHandlers() {
+ // When the window resizes, we need to refresh active editors.
+ var resizeTimer;
+ on(window, "resize", function () {
+ if (resizeTimer == null) { resizeTimer = setTimeout(function () {
+ resizeTimer = null;
+ forEachCodeMirror(onResize);
+ }, 100); }
+ });
+ // When the window loses focus, we want to show the editor as blurred
+ on(window, "blur", function () { return forEachCodeMirror(onBlur); });
+ }
+ // Called when the window resizes
+ function onResize(cm) {
+ var d = cm.display;
+ // Might be a text scaling operation, clear size caches.
+ d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null;
+ d.scrollbarsClipped = false;
+ cm.setSize();
+ }
+
+ var keyNames = {
+ 3: "Pause", 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",
+ 106: "*", 107: "=", 109: "-", 110: ".", 111: "/", 145: "ScrollLock",
+ 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\",
+ 221: "]", 222: "'", 224: "Mod", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete",
+ 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"
+ };
+
+ // Number keys
+ for (var i = 0; i < 10; i++) { keyNames[i + 48] = keyNames[i + 96] = String(i); }
+ // Alphabetic keys
+ for (var i$1 = 65; i$1 <= 90; i$1++) { keyNames[i$1] = String.fromCharCode(i$1); }
+ // Function keys
+ for (var i$2 = 1; i$2 <= 12; i$2++) { keyNames[i$2 + 111] = keyNames[i$2 + 63235] = "F" + i$2; }
+
+ var 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-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown",
+ "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"
+ };
+ // 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",
+ "Ctrl-O": "openLine"
+ };
+ keyMap.macDefault = {
+ "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo",
+ "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft",
+ "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "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": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight",
+ "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd",
+ "fallthrough": ["basic", "emacsy"]
+ };
+ keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault;
+
+ // KEYMAP DISPATCH
+
+ function normalizeKeyName(name) {
+ var parts = name.split(/-(?!$)/);
+ name = parts[parts.length - 1];
+ var alt, ctrl, shift, cmd;
+ for (var i = 0; i < parts.length - 1; i++) {
+ var mod = parts[i];
+ if (/^(cmd|meta|m)$/i.test(mod)) { cmd = true; }
+ else if (/^a(lt)?$/i.test(mod)) { alt = true; }
+ else if (/^(c|ctrl|control)$/i.test(mod)) { ctrl = true; }
+ else if (/^s(hift)?$/i.test(mod)) { shift = true; }
+ else { throw new Error("Unrecognized modifier name: " + mod) }
+ }
+ if (alt) { name = "Alt-" + name; }
+ if (ctrl) { name = "Ctrl-" + name; }
+ if (cmd) { name = "Cmd-" + name; }
+ if (shift) { name = "Shift-" + name; }
+ return name
+ }
+
+ // This is a kludge to keep keymaps mostly working as raw objects
+ // (backwards compatibility) while at the same time support features
+ // like normalization and multi-stroke key bindings. It compiles a
+ // new normalized keymap, and then updates the old object to reflect
+ // this.
+ function normalizeKeyMap(keymap) {
+ var copy = {};
+ for (var keyname in keymap) { if (keymap.hasOwnProperty(keyname)) {
+ var value = keymap[keyname];
+ if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) { continue }
+ if (value == "...") { delete keymap[keyname]; continue }
+
+ var keys = map(keyname.split(" "), normalizeKeyName);
+ for (var i = 0; i < keys.length; i++) {
+ var val = (void 0), name = (void 0);
+ if (i == keys.length - 1) {
+ name = keys.join(" ");
+ val = value;
+ } else {
+ name = keys.slice(0, i + 1).join(" ");
+ val = "...";
+ }
+ var prev = copy[name];
+ if (!prev) { copy[name] = val; }
+ else if (prev != val) { throw new Error("Inconsistent bindings for " + name) }
+ }
+ delete keymap[keyname];
+ } }
+ for (var prop in copy) { keymap[prop] = copy[prop]; }
+ return keymap
+ }
+
+ function lookupKey(key, map, handle, context) {
+ map = getKeyMap(map);
+ var found = map.call ? map.call(key, context) : map[key];
+ if (found === false) { return "nothing" }
+ if (found === "...") { return "multi" }
+ if (found != null && handle(found)) { return "handled" }
+
+ if (map.fallthrough) {
+ if (Object.prototype.toString.call(map.fallthrough) != "[object Array]")
+ { return lookupKey(key, map.fallthrough, handle, context) }
+ for (var i = 0; i < map.fallthrough.length; i++) {
+ var result = lookupKey(key, map.fallthrough[i], handle, context);
+ if (result) { return result }
+ }
+ }
+ }
+
+ // Modifier key presses don't count as 'real' key presses for the
+ // purpose of keymap fallthrough.
+ function isModifierKey(value) {
+ var name = typeof value == "string" ? value : keyNames[value.keyCode];
+ return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"
+ }
+
+ function addModifierNames(name, event, noShift) {
+ var base = name;
+ if (event.altKey && base != "Alt") { name = "Alt-" + name; }
+ if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") { name = "Ctrl-" + name; }
+ if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Mod") { name = "Cmd-" + name; }
+ if (!noShift && event.shiftKey && base != "Shift") { name = "Shift-" + name; }
+ return name
+ }
+
+ // Look up the name of a key as indicated by an event object.
+ function keyName(event, noShift) {
+ if (presto && event.keyCode == 34 && event["char"]) { return false }
+ var name = keyNames[event.keyCode];
+ if (name == null || event.altGraphKey) { return false }
+ // Ctrl-ScrollLock has keyCode 3, same as Ctrl-Pause,
+ // so we'll use event.code when available (Chrome 48+, FF 38+, Safari 10.1+)
+ if (event.keyCode == 3 && event.code) { name = event.code; }
+ return addModifierNames(name, event, noShift)
+ }
+
+ function getKeyMap(val) {
+ return typeof val == "string" ? keyMap[val] : val
+ }
+
+ // 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);
+ });
+ }
+
+ function moveCharLogically(line, ch, dir) {
+ var target = skipExtendingChars(line.text, ch + dir, dir);
+ return target < 0 || target > line.text.length ? null : target
+ }
+
+ function moveLogically(line, start, dir) {
+ var ch = moveCharLogically(line, start.ch, dir);
+ return ch == null ? null : new Pos(start.line, ch, dir < 0 ? "after" : "before")
+ }
+
+ function endOfLine(visually, cm, lineObj, lineNo, dir) {
+ if (visually) {
+ if (cm.doc.direction == "rtl") { dir = -dir; }
+ var order = getOrder(lineObj, cm.doc.direction);
+ if (order) {
+ var part = dir < 0 ? lst(order) : order[0];
+ var moveInStorageOrder = (dir < 0) == (part.level == 1);
+ var sticky = moveInStorageOrder ? "after" : "before";
+ var ch;
+ // With a wrapped rtl chunk (possibly spanning multiple bidi parts),
+ // it could be that the last bidi part is not on the last visual line,
+ // since visual lines contain content order-consecutive chunks.
+ // Thus, in rtl, we are looking for the first (content-order) character
+ // in the rtl chunk that is on the last line (that is, the same line
+ // as the last (content-order) character).
+ if (part.level > 0 || cm.doc.direction == "rtl") {
+ var prep = prepareMeasureForLine(cm, lineObj);
+ ch = dir < 0 ? lineObj.text.length - 1 : 0;
+ var targetTop = measureCharPrepared(cm, prep, ch).top;
+ ch = findFirst(function (ch) { return measureCharPrepared(cm, prep, ch).top == targetTop; }, (dir < 0) == (part.level == 1) ? part.from : part.to - 1, ch);
+ if (sticky == "before") { ch = moveCharLogically(lineObj, ch, 1); }
+ } else { ch = dir < 0 ? part.to : part.from; }
+ return new Pos(lineNo, ch, sticky)
+ }
+ }
+ return new Pos(lineNo, dir < 0 ? lineObj.text.length : 0, dir < 0 ? "before" : "after")
+ }
+
+ function moveVisually(cm, line, start, dir) {
+ var bidi = getOrder(line, cm.doc.direction);
+ if (!bidi) { return moveLogically(line, start, dir) }
+ if (start.ch >= line.text.length) {
+ start.ch = line.text.length;
+ start.sticky = "before";
+ } else if (start.ch <= 0) {
+ start.ch = 0;
+ start.sticky = "after";
+ }
+ var partPos = getBidiPartAt(bidi, start.ch, start.sticky), part = bidi[partPos];
+ if (cm.doc.direction == "ltr" && part.level % 2 == 0 && (dir > 0 ? part.to > start.ch : part.from < start.ch)) {
+ // Case 1: We move within an ltr part in an ltr editor. Even with wrapped lines,
+ // nothing interesting happens.
+ return moveLogically(line, start, dir)
+ }
+
+ var mv = function (pos, dir) { return moveCharLogically(line, pos instanceof Pos ? pos.ch : pos, dir); };
+ var prep;
+ var getWrappedLineExtent = function (ch) {
+ if (!cm.options.lineWrapping) { return {begin: 0, end: line.text.length} }
+ prep = prep || prepareMeasureForLine(cm, line);
+ return wrappedLineExtentChar(cm, line, prep, ch)
+ };
+ var wrappedLineExtent = getWrappedLineExtent(start.sticky == "before" ? mv(start, -1) : start.ch);
+
+ if (cm.doc.direction == "rtl" || part.level == 1) {
+ var moveInStorageOrder = (part.level == 1) == (dir < 0);
+ var ch = mv(start, moveInStorageOrder ? 1 : -1);
+ if (ch != null && (!moveInStorageOrder ? ch >= part.from && ch >= wrappedLineExtent.begin : ch <= part.to && ch <= wrappedLineExtent.end)) {
+ // Case 2: We move within an rtl part or in an rtl editor on the same visual line
+ var sticky = moveInStorageOrder ? "before" : "after";
+ return new Pos(start.line, ch, sticky)
+ }
+ }
+
+ // Case 3: Could not move within this bidi part in this visual line, so leave
+ // the current bidi part
+
+ var searchInVisualLine = function (partPos, dir, wrappedLineExtent) {
+ var getRes = function (ch, moveInStorageOrder) { return moveInStorageOrder
+ ? new Pos(start.line, mv(ch, 1), "before")
+ : new Pos(start.line, ch, "after"); };
+
+ for (; partPos >= 0 && partPos < bidi.length; partPos += dir) {
+ var part = bidi[partPos];
+ var moveInStorageOrder = (dir > 0) == (part.level != 1);
+ var ch = moveInStorageOrder ? wrappedLineExtent.begin : mv(wrappedLineExtent.end, -1);
+ if (part.from <= ch && ch < part.to) { return getRes(ch, moveInStorageOrder) }
+ ch = moveInStorageOrder ? part.from : mv(part.to, -1);
+ if (wrappedLineExtent.begin <= ch && ch < wrappedLineExtent.end) { return getRes(ch, moveInStorageOrder) }
+ }
+ };
+
+ // Case 3a: Look for other bidi parts on the same visual line
+ var res = searchInVisualLine(partPos + dir, dir, wrappedLineExtent);
+ if (res) { return res }
+
+ // Case 3b: Look for other bidi parts on the next visual line
+ var nextCh = dir > 0 ? wrappedLineExtent.end : mv(wrappedLineExtent.begin, -1);
+ if (nextCh != null && !(dir > 0 && nextCh == line.text.length)) {
+ res = searchInVisualLine(dir > 0 ? 0 : bidi.length - 1, dir, getWrappedLineExtent(nextCh));
+ if (res) { return res }
+ }
+
+ // Case 4: Nowhere to move
+ return null
+ }
+
+ // Commands are parameter-less actions that can be performed on an
+ // editor, mostly used for keybindings.
+ var commands = {
+ selectAll: selectAll,
+ singleSelection: function (cm) { return cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); },
+ killLine: function (cm) { return 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) { return deleteNearSelection(cm, function (range) { return ({
+ from: Pos(range.from().line, 0),
+ to: clipPos(cm.doc, Pos(range.to().line + 1, 0))
+ }); }); },
+ delLineLeft: function (cm) { return deleteNearSelection(cm, function (range) { return ({
+ from: Pos(range.from().line, 0), to: range.from()
+ }); }); },
+ delWrappedLineLeft: function (cm) { return deleteNearSelection(cm, function (range) {
+ var top = cm.charCoords(range.head, "div").top + 5;
+ var leftPos = cm.coordsChar({left: 0, top: top}, "div");
+ return {from: leftPos, to: range.from()}
+ }); },
+ delWrappedLineRight: function (cm) { return deleteNearSelection(cm, function (range) {
+ var top = cm.charCoords(range.head, "div").top + 5;
+ var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div");
+ return {from: range.from(), to: rightPos }
+ }); },
+ undo: function (cm) { return cm.undo(); },
+ redo: function (cm) { return cm.redo(); },
+ undoSelection: function (cm) { return cm.undoSelection(); },
+ redoSelection: function (cm) { return cm.redoSelection(); },
+ goDocStart: function (cm) { return cm.extendSelection(Pos(cm.firstLine(), 0)); },
+ goDocEnd: function (cm) { return cm.extendSelection(Pos(cm.lastLine())); },
+ goLineStart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); },
+ {origin: "+move", bias: 1}
+ ); },
+ goLineStartSmart: function (cm) { return cm.extendSelectionsBy(function (range) { return lineStartSmart(cm, range.head); },
+ {origin: "+move", bias: 1}
+ ); },
+ goLineEnd: function (cm) { return cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); },
+ {origin: "+move", bias: -1}
+ ); },
+ goLineRight: function (cm) { return cm.extendSelectionsBy(function (range) {
+ var top = cm.cursorCoords(range.head, "div").top + 5;
+ return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div")
+ }, sel_move); },
+ goLineLeft: function (cm) { return cm.extendSelectionsBy(function (range) {
+ var top = cm.cursorCoords(range.head, "div").top + 5;
+ return cm.coordsChar({left: 0, top: top}, "div")
+ }, sel_move); },
+ goLineLeftSmart: function (cm) { return cm.extendSelectionsBy(function (range) {
+ var top = cm.cursorCoords(range.head, "div").top + 5;
+ var pos = cm.coordsChar({left: 0, top: top}, "div");
+ if (pos.ch < cm.getLine(pos.line).search(/\S/)) { return lineStartSmart(cm, range.head) }
+ return pos
+ }, sel_move); },
+ goLineUp: function (cm) { return cm.moveV(-1, "line"); },
+ goLineDown: function (cm) { return cm.moveV(1, "line"); },
+ goPageUp: function (cm) { return cm.moveV(-1, "page"); },
+ goPageDown: function (cm) { return cm.moveV(1, "page"); },
+ goCharLeft: function (cm) { return cm.moveH(-1, "char"); },
+ goCharRight: function (cm) { return cm.moveH(1, "char"); },
+ goColumnLeft: function (cm) { return cm.moveH(-1, "column"); },
+ goColumnRight: function (cm) { return cm.moveH(1, "column"); },
+ goWordLeft: function (cm) { return cm.moveH(-1, "word"); },
+ goGroupRight: function (cm) { return cm.moveH(1, "group"); },
+ goGroupLeft: function (cm) { return cm.moveH(-1, "group"); },
+ goWordRight: function (cm) { return cm.moveH(1, "word"); },
+ delCharBefore: function (cm) { return cm.deleteH(-1, "codepoint"); },
+ delCharAfter: function (cm) { return cm.deleteH(1, "char"); },
+ delWordBefore: function (cm) { return cm.deleteH(-1, "word"); },
+ delWordAfter: function (cm) { return cm.deleteH(1, "word"); },
+ delGroupBefore: function (cm) { return cm.deleteH(-1, "group"); },
+ delGroupAfter: function (cm) { return cm.deleteH(1, "group"); },
+ indentAuto: function (cm) { return cm.indentSelection("smart"); },
+ indentMore: function (cm) { return cm.indentSelection("add"); },
+ indentLess: function (cm) { return cm.indentSelection("subtract"); },
+ insertTab: function (cm) { return cm.replaceSelection("\t"); },
+ insertSoftTab: function (cm) {
+ var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize;
+ for (var i = 0; i < ranges.length; i++) {
+ var pos = ranges[i].from();
+ var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize);
+ spaces.push(spaceStr(tabSize - col % tabSize));
+ }
+ cm.replaceSelections(spaces);
+ },
+ defaultTab: function (cm) {
+ if (cm.somethingSelected()) { cm.indentSelection("add"); }
+ else { cm.execCommand("insertTab"); }
+ },
+ // Swap the two chars left and right of each selection's head.
+ // Move cursor behind the two swapped characters afterwards.
+ //
+ // Doesn't consider line feeds a character.
+ // Doesn't scan more than one line above to find a character.
+ // Doesn't do anything on an empty line.
+ // Doesn't do anything with non-empty selections.
+ transposeChars: function (cm) { return runInOp(cm, function () {
+ var ranges = cm.listSelections(), newSel = [];
+ for (var i = 0; i < ranges.length; i++) {
+ if (!ranges[i].empty()) { continue }
+ var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text;
+ if (line) {
+ if (cur.ch == line.length) { cur = new Pos(cur.line, cur.ch - 1); }
+ if (cur.ch > 0) {
+ cur = new Pos(cur.line, cur.ch + 1);
+ cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2),
+ Pos(cur.line, cur.ch - 2), cur, "+transpose");
+ } else if (cur.line > cm.doc.first) {
+ var prev = getLine(cm.doc, cur.line - 1).text;
+ if (prev) {
+ cur = new Pos(cur.line, 1);
+ cm.replaceRange(line.charAt(0) + cm.doc.lineSeparator() +
+ prev.charAt(prev.length - 1),
+ Pos(cur.line - 1, prev.length - 1), cur, "+transpose");
+ }
+ }
+ }
+ newSel.push(new Range(cur, cur));
+ }
+ cm.setSelections(newSel);
+ }); },
+ newlineAndIndent: function (cm) { return runInOp(cm, function () {
+ var sels = cm.listSelections();
+ for (var i = sels.length - 1; i >= 0; i--)
+ { cm.replaceRange(cm.doc.lineSeparator(), sels[i].anchor, sels[i].head, "+input"); }
+ sels = cm.listSelections();
+ for (var i$1 = 0; i$1 < sels.length; i$1++)
+ { cm.indentLine(sels[i$1].from().line, null, true); }
+ ensureCursorVisible(cm);
+ }); },
+ openLine: function (cm) { return cm.replaceSelection("\n", "start"); },
+ toggleOverwrite: function (cm) { return cm.toggleOverwrite(); }
+ };
+
+
+ function lineStart(cm, lineN) {
+ var line = getLine(cm.doc, lineN);
+ var visual = visualLine(line);
+ if (visual != line) { lineN = lineNo(visual); }
+ return endOfLine(true, cm, visual, lineN, 1)
+ }
+ function lineEnd(cm, lineN) {
+ var line = getLine(cm.doc, lineN);
+ var visual = visualLineEnd(line);
+ if (visual != line) { lineN = lineNo(visual); }
+ return endOfLine(true, cm, line, lineN, -1)
+ }
+ function lineStartSmart(cm, pos) {
+ var start = lineStart(cm, pos.line);
+ var line = getLine(cm.doc, start.line);
+ var order = getOrder(line, cm.doc.direction);
+ if (!order || order[0].level == 0) {
+ var firstNonWS = Math.max(start.ch, line.text.search(/\S/));
+ var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch;
+ return Pos(start.line, inWS ? 0 : firstNonWS, start.sticky)
+ }
+ return start
+ }
+
+ // 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
+ cm.display.input.ensurePolled();
+ var prevShift = cm.display.shift, done = false;
+ try {
+ if (cm.isReadOnly()) { 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
+ }
+
+ function lookupKeyForEditor(cm, name, handle) {
+ for (var i = 0; i < cm.state.keyMaps.length; i++) {
+ var result = lookupKey(name, cm.state.keyMaps[i], handle, cm);
+ if (result) { return result }
+ }
+ return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm))
+ || lookupKey(name, cm.options.keyMap, handle, cm)
+ }
+
+ // Note that, despite the name, this function is also used to check
+ // for bound mouse clicks.
+
+ var stopSeq = new Delayed;
+
+ function dispatchKey(cm, name, e, handle) {
+ var seq = cm.state.keySeq;
+ if (seq) {
+ if (isModifierKey(name)) { return "handled" }
+ if (/\'$/.test(name))
+ { cm.state.keySeq = null; }
+ else
+ { stopSeq.set(50, function () {
+ if (cm.state.keySeq == seq) {
+ cm.state.keySeq = null;
+ cm.display.input.reset();
+ }
+ }); }
+ if (dispatchKeyInner(cm, seq + " " + name, e, handle)) { return true }
+ }
+ return dispatchKeyInner(cm, name, e, handle)
+ }
+
+ function dispatchKeyInner(cm, name, e, handle) {
+ var result = lookupKeyForEditor(cm, name, handle);
+
+ if (result == "multi")
+ { cm.state.keySeq = name; }
+ if (result == "handled")
+ { signalLater(cm, "keyHandled", cm, name, e); }
+
+ if (result == "handled" || result == "multi") {
+ e_preventDefault(e);
+ restartBlink(cm);
+ }
+
+ return !!result
+ }
+
+ // Handle a key from the keydown event.
+ function handleKeyBinding(cm, e) {
+ var name = keyName(e, true);
+ if (!name) { return false }
+
+ if (e.shiftKey && !cm.state.keySeq) {
+ // 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-'.
+ return dispatchKey(cm, "Shift-" + name, e, function (b) { return doHandleBinding(cm, b, true); })
+ || dispatchKey(cm, name, e, function (b) {
+ if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion)
+ { return doHandleBinding(cm, b) }
+ })
+ } else {
+ return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); })
+ }
+ }
+
+ // Handle a key from the keypress event
+ function handleCharBinding(cm, e, ch) {
+ return dispatchKey(cm, "'" + ch + "'", e, function (b) { return doHandleBinding(cm, b, true); })
+ }
+
+ var lastStoppedKey = null;
+ function onKeyDown(e) {
+ var cm = this;
+ if (e.target && e.target != cm.display.input.getField()) { return }
+ cm.curOp.focus = activeElt();
+ if (signalDOMEvent(cm, e)) { return }
+ // IE does strange things with escape.
+ if (ie && ie_version < 11 && 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"); }
+ }
+ if (gecko && !mac && !handled && code == 46 && e.shiftKey && !e.ctrlKey && document.execCommand)
+ { document.execCommand("cut"); }
+
+ // Turn mouse into crosshair when Alt is held on Mac.
+ if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className))
+ { showCrossHair(cm); }
+ }
+
+ function showCrossHair(cm) {
+ var lineDiv = cm.display.lineDiv;
+ addClass(lineDiv, "CodeMirror-crosshair");
+
+ function up(e) {
+ if (e.keyCode == 18 || !e.altKey) {
+ rmClass(lineDiv, "CodeMirror-crosshair");
+ off(document, "keyup", up);
+ off(document, "mouseover", up);
+ }
+ }
+ on(document, "keyup", up);
+ on(document, "mouseover", up);
+ }
+
+ function onKeyUp(e) {
+ if (e.keyCode == 16) { this.doc.sel.shift = false; }
+ signalDOMEvent(this, e);
+ }
+
+ function onKeyPress(e) {
+ var cm = this;
+ if (e.target && e.target != cm.display.input.getField()) { return }
+ if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) { 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)) && handleKeyBinding(cm, e)) { return }
+ var ch = String.fromCharCode(charCode == null ? keyCode : charCode);
+ // Some browsers fire keypress events for backspace
+ if (ch == "\x08") { return }
+ if (handleCharBinding(cm, e, ch)) { return }
+ cm.display.input.onKeyPress(e);
+ }
+
+ var DOUBLECLICK_DELAY = 400;
+
+ var PastClick = function(time, pos, button) {
+ this.time = time;
+ this.pos = pos;
+ this.button = button;
+ };
+
+ PastClick.prototype.compare = function (time, pos, button) {
+ return this.time + DOUBLECLICK_DELAY > time &&
+ cmp(pos, this.pos) == 0 && button == this.button
+ };
+
+ var lastClick, lastDoubleClick;
+ function clickRepeat(pos, button) {
+ var now = +new Date;
+ if (lastDoubleClick && lastDoubleClick.compare(now, pos, button)) {
+ lastClick = lastDoubleClick = null;
+ return "triple"
+ } else if (lastClick && lastClick.compare(now, pos, button)) {
+ lastDoubleClick = new PastClick(now, pos, button);
+ lastClick = null;
+ return "double"
+ } else {
+ lastClick = new PastClick(now, pos, button);
+ lastDoubleClick = null;
+ return "single"
+ }
+ }
+
+ // 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) {
+ var cm = this, display = cm.display;
+ if (signalDOMEvent(cm, e) || display.activeTouch && display.input.supportsTouch()) { return }
+ display.input.ensurePolled();
+ 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 () { return display.scroller.draggable = true; }, 100);
+ }
+ return
+ }
+ if (clickInGutter(cm, e)) { return }
+ var pos = posFromMouse(cm, e), button = e_button(e), repeat = pos ? clickRepeat(pos, button) : "single";
+ window.focus();
+
+ // #3261: make sure, that we're not starting a second selection
+ if (button == 1 && cm.state.selectingText)
+ { cm.state.selectingText(e); }
+
+ if (pos && handleMappedButton(cm, button, pos, repeat, e)) { return }
+
+ if (button == 1) {
+ if (pos) { leftButtonDown(cm, pos, repeat, e); }
+ else if (e_target(e) == display.scroller) { e_preventDefault(e); }
+ } else if (button == 2) {
+ if (pos) { extendSelection(cm.doc, pos); }
+ setTimeout(function () { return display.input.focus(); }, 20);
+ } else if (button == 3) {
+ if (captureRightClick) { cm.display.input.onContextMenu(e); }
+ else { delayBlurEvent(cm); }
+ }
+ }
+
+ function handleMappedButton(cm, button, pos, repeat, event) {
+ var name = "Click";
+ if (repeat == "double") { name = "Double" + name; }
+ else if (repeat == "triple") { name = "Triple" + name; }
+ name = (button == 1 ? "Left" : button == 2 ? "Middle" : "Right") + name;
+
+ return dispatchKey(cm, addModifierNames(name, event), event, function (bound) {
+ if (typeof bound == "string") { bound = commands[bound]; }
+ if (!bound) { return false }
+ var done = false;
+ try {
+ if (cm.isReadOnly()) { cm.state.suppressEdits = true; }
+ done = bound(cm, pos) != Pass;
+ } finally {
+ cm.state.suppressEdits = false;
+ }
+ return done
+ })
+ }
+
+ function configureMouse(cm, repeat, event) {
+ var option = cm.getOption("configureMouse");
+ var value = option ? option(cm, repeat, event) : {};
+ if (value.unit == null) {
+ var rect = chromeOS ? event.shiftKey && event.metaKey : event.altKey;
+ value.unit = rect ? "rectangle" : repeat == "single" ? "char" : repeat == "double" ? "word" : "line";
+ }
+ if (value.extend == null || cm.doc.extend) { value.extend = cm.doc.extend || event.shiftKey; }
+ if (value.addNew == null) { value.addNew = mac ? event.metaKey : event.ctrlKey; }
+ if (value.moveOnDrag == null) { value.moveOnDrag = !(mac ? event.altKey : event.ctrlKey); }
+ return value
+ }
+
+ function leftButtonDown(cm, pos, repeat, event) {
+ if (ie) { setTimeout(bind(ensureFocus, cm), 0); }
+ else { cm.curOp.focus = activeElt(); }
+
+ var behavior = configureMouse(cm, repeat, event);
+
+ var sel = cm.doc.sel, contained;
+ if (cm.options.dragDrop && dragAndDrop && !cm.isReadOnly() &&
+ repeat == "single" && (contained = sel.contains(pos)) > -1 &&
+ (cmp((contained = sel.ranges[contained]).from(), pos) < 0 || pos.xRel > 0) &&
+ (cmp(contained.to(), pos) > 0 || pos.xRel < 0))
+ { leftButtonStartDrag(cm, event, pos, behavior); }
+ else
+ { leftButtonSelect(cm, event, pos, behavior); }
+ }
+
+ // 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, event, pos, behavior) {
+ var display = cm.display, moved = false;
+ var dragEnd = operation(cm, function (e) {
+ if (webkit) { display.scroller.draggable = false; }
+ cm.state.draggingText = false;
+ off(display.wrapper.ownerDocument, "mouseup", dragEnd);
+ off(display.wrapper.ownerDocument, "mousemove", mouseMove);
+ off(display.scroller, "dragstart", dragStart);
+ off(display.scroller, "drop", dragEnd);
+ if (!moved) {
+ e_preventDefault(e);
+ if (!behavior.addNew)
+ { extendSelection(cm.doc, pos, null, null, behavior.extend); }
+ // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081)
+ if ((webkit && !safari) || ie && ie_version == 9)
+ { setTimeout(function () {display.wrapper.ownerDocument.body.focus({preventScroll: true}); display.input.focus();}, 20); }
+ else
+ { display.input.focus(); }
+ }
+ });
+ var mouseMove = function(e2) {
+ moved = moved || Math.abs(event.clientX - e2.clientX) + Math.abs(event.clientY - e2.clientY) >= 10;
+ };
+ var dragStart = function () { return moved = true; };
+ // Let the drag handler handle this.
+ if (webkit) { display.scroller.draggable = true; }
+ cm.state.draggingText = dragEnd;
+ dragEnd.copy = !behavior.moveOnDrag;
+ // IE's approach to draggable
+ if (display.scroller.dragDrop) { display.scroller.dragDrop(); }
+ on(display.wrapper.ownerDocument, "mouseup", dragEnd);
+ on(display.wrapper.ownerDocument, "mousemove", mouseMove);
+ on(display.scroller, "dragstart", dragStart);
+ on(display.scroller, "drop", dragEnd);
+
+ delayBlurEvent(cm);
+ setTimeout(function () { return display.input.focus(); }, 20);
+ }
+
+ function rangeForUnit(cm, pos, unit) {
+ if (unit == "char") { return new Range(pos, pos) }
+ if (unit == "word") { return cm.findWordAt(pos) }
+ if (unit == "line") { return new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))) }
+ var result = unit(cm, pos);
+ return new Range(result.from, result.to)
+ }
+
+ // Normal selection, as opposed to text dragging.
+ function leftButtonSelect(cm, event, start, behavior) {
+ var display = cm.display, doc = cm.doc;
+ e_preventDefault(event);
+
+ var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges;
+ if (behavior.addNew && !behavior.extend) {
+ ourIndex = doc.sel.contains(start);
+ if (ourIndex > -1)
+ { ourRange = ranges[ourIndex]; }
+ else
+ { ourRange = new Range(start, start); }
+ } else {
+ ourRange = doc.sel.primary();
+ ourIndex = doc.sel.primIndex;
+ }
+
+ if (behavior.unit == "rectangle") {
+ if (!behavior.addNew) { ourRange = new Range(start, start); }
+ start = posFromMouse(cm, event, true, true);
+ ourIndex = -1;
+ } else {
+ var range = rangeForUnit(cm, start, behavior.unit);
+ if (behavior.extend)
+ { ourRange = extendRange(ourRange, range.anchor, range.head, behavior.extend); }
+ else
+ { ourRange = range; }
+ }
+
+ if (!behavior.addNew) {
+ ourIndex = 0;
+ setSelection(doc, new Selection([ourRange], 0), sel_mouse);
+ startSel = doc.sel;
+ } else if (ourIndex == -1) {
+ ourIndex = ranges.length;
+ setSelection(doc, normalizeSelection(cm, ranges.concat([ourRange]), ourIndex),
+ {scroll: false, origin: "*mouse"});
+ } else if (ranges.length > 1 && ranges[ourIndex].empty() && behavior.unit == "char" && !behavior.extend) {
+ setSelection(doc, normalizeSelection(cm, ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0),
+ {scroll: false, origin: "*mouse"});
+ startSel = doc.sel;
+ } else {
+ replaceOneSelection(doc, ourIndex, ourRange, sel_mouse);
+ }
+
+ var lastPos = start;
+ function extendTo(pos) {
+ if (cmp(lastPos, pos) == 0) { return }
+ lastPos = pos;
+
+ if (behavior.unit == "rectangle") {
+ 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(cm, startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex),
+ {origin: "*mouse", scroll: false});
+ cm.scrollIntoView(pos);
+ } else {
+ var oldRange = ourRange;
+ var range = rangeForUnit(cm, pos, behavior.unit);
+ var anchor = oldRange.anchor, head;
+ 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$1 = startSel.ranges.slice(0);
+ ranges$1[ourIndex] = bidiSimplify(cm, new Range(clipPos(doc, anchor), head));
+ setSelection(doc, normalizeSelection(cm, ranges$1, 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, behavior.unit == "rectangle");
+ if (!cur) { return }
+ if (cmp(cur, lastPos) != 0) {
+ cm.curOp.focus = activeElt();
+ 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) {
+ cm.state.selectingText = false;
+ counter = Infinity;
+ // If e is null or undefined we interpret this as someone trying
+ // to explicitly cancel the selection rather than the user
+ // letting go of the mouse button.
+ if (e) {
+ e_preventDefault(e);
+ display.input.focus();
+ }
+ off(display.wrapper.ownerDocument, "mousemove", move);
+ off(display.wrapper.ownerDocument, "mouseup", up);
+ doc.history.lastSelOrigin = null;
+ }
+
+ var move = operation(cm, function (e) {
+ if (e.buttons === 0 || !e_button(e)) { done(e); }
+ else { extend(e); }
+ });
+ var up = operation(cm, done);
+ cm.state.selectingText = up;
+ on(display.wrapper.ownerDocument, "mousemove", move);
+ on(display.wrapper.ownerDocument, "mouseup", up);
+ }
+
+ // Used when mouse-selecting to adjust the anchor to the proper side
+ // of a bidi jump depending on the visual position of the head.
+ function bidiSimplify(cm, range) {
+ var anchor = range.anchor;
+ var head = range.head;
+ var anchorLine = getLine(cm.doc, anchor.line);
+ if (cmp(anchor, head) == 0 && anchor.sticky == head.sticky) { return range }
+ var order = getOrder(anchorLine);
+ if (!order) { return range }
+ var index = getBidiPartAt(order, anchor.ch, anchor.sticky), part = order[index];
+ if (part.from != anchor.ch && part.to != anchor.ch) { return range }
+ var boundary = index + ((part.from == anchor.ch) == (part.level != 1) ? 0 : 1);
+ if (boundary == 0 || boundary == order.length) { return range }
+
+ // Compute the relative visual position of the head compared to the
+ // anchor (<0 is to the left, >0 to the right)
+ var leftSide;
+ if (head.line != anchor.line) {
+ leftSide = (head.line - anchor.line) * (cm.doc.direction == "ltr" ? 1 : -1) > 0;
+ } else {
+ var headIndex = getBidiPartAt(order, head.ch, head.sticky);
+ var dir = headIndex - index || (head.ch - anchor.ch) * (part.level == 1 ? -1 : 1);
+ if (headIndex == boundary - 1 || headIndex == boundary)
+ { leftSide = dir < 0; }
+ else
+ { leftSide = dir > 0; }
+ }
+
+ var usePart = order[boundary + (leftSide ? -1 : 0)];
+ var from = leftSide == (usePart.level == 1);
+ var ch = from ? usePart.from : usePart.to, sticky = from ? "after" : "before";
+ return anchor.ch == ch && anchor.sticky == sticky ? range : new Range(new Pos(anchor.line, ch, sticky), head)
+ }
+
+
+ // Determines whether an event happened in the gutter, and fires the
+ // handlers for the corresponding event.
+ function gutterEvent(cm, e, type, prevent) {
+ var mX, mY;
+ if (e.touches) {
+ mX = e.touches[0].clientX;
+ mY = e.touches[0].clientY;
+ } else {
+ try { mX = e.clientX; mY = e.clientY; }
+ catch(e$1) { 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.display.gutterSpecs.length; ++i) {
+ var g = display.gutters.childNodes[i];
+ if (g && g.getBoundingClientRect().right >= mX) {
+ var line = lineAtHeight(cm.doc, mY);
+ var gutter = cm.display.gutterSpecs[i];
+ signal(cm, type, cm, line, gutter.className, e);
+ return e_defaultPrevented(e)
+ }
+ }
+ }
+
+ function clickInGutter(cm, e) {
+ return gutterEvent(cm, e, "gutterClick", true)
+ }
+
+ // CONTEXT MENU HANDLING
+
+ // 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 (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) { return }
+ if (signalDOMEvent(cm, e, "contextmenu")) { return }
+ if (!captureRightClick) { cm.display.input.onContextMenu(e); }
+ }
+
+ function contextMenuInGutter(cm, e) {
+ if (!hasHandler(cm, "gutterContextMenu")) { return false }
+ return gutterEvent(cm, e, "gutterContextMenu", false)
+ }
+
+ 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);
+ }
+
+ var Init = {toString: function(){return "CodeMirror.Init"}};
+
+ var defaults = {};
+ var optionHandlers = {};
+
+ function defineOptions(CodeMirror) {
+ 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; }
+ }
+
+ CodeMirror.defineOption = option;
+
+ // Passed to option handlers when there is no old value.
+ CodeMirror.Init = 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) { return 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("lineSeparator", null, function (cm, val) {
+ cm.doc.lineSep = val;
+ if (!val) { return }
+ var newBreaks = [], lineNo = cm.doc.first;
+ cm.doc.iter(function (line) {
+ for (var pos = 0;;) {
+ var found = line.text.indexOf(val, pos);
+ if (found == -1) { break }
+ pos = found + val.length;
+ newBreaks.push(Pos(lineNo, found));
+ }
+ lineNo++;
+ });
+ for (var i = newBreaks.length - 1; i >= 0; i--)
+ { replaceRange(cm.doc, val, newBreaks[i], Pos(newBreaks[i].line, newBreaks[i].ch + val.length)); }
+ });
+ option("specialChars", /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200c\u200e\u200f\u2028\u2029\ufeff\ufff9-\ufffc]/g, function (cm, val, old) {
+ cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g");
+ if (old != Init) { cm.refresh(); }
+ });
+ option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) { return cm.refresh(); }, true);
+ option("electricChars", true);
+ option("inputStyle", mobile ? "contenteditable" : "textarea", function () {
+ throw new Error("inputStyle can not (yet) be changed in a running editor") // FIXME
+ }, true);
+ option("spellcheck", false, function (cm, val) { return cm.getInputField().spellcheck = val; }, true);
+ option("autocorrect", false, function (cm, val) { return cm.getInputField().autocorrect = val; }, true);
+ option("autocapitalize", false, function (cm, val) { return cm.getInputField().autocapitalize = val; }, true);
+ option("rtlMoveVisually", !windows);
+ option("wholeLineUpdateBefore", true);
+
+ option("theme", "default", function (cm) {
+ themeChanged(cm);
+ updateGutters(cm);
+ }, true);
+ option("keyMap", "default", function (cm, val, old) {
+ var next = getKeyMap(val);
+ var prev = old != Init && getKeyMap(old);
+ if (prev && prev.detach) { prev.detach(cm, next); }
+ if (next.attach) { next.attach(cm, prev || null); }
+ });
+ option("extraKeys", null);
+ option("configureMouse", null);
+
+ option("lineWrapping", false, wrappingChanged, true);
+ option("gutters", [], function (cm, val) {
+ cm.display.gutterSpecs = getGutters(val, cm.options.lineNumbers);
+ updateGutters(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, function (cm) { return updateScrollbars(cm); }, true);
+ option("scrollbarStyle", "native", function (cm) {
+ initScrollbars(cm);
+ updateScrollbars(cm);
+ cm.display.scrollbars.setScrollTop(cm.doc.scrollTop);
+ cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft);
+ }, true);
+ option("lineNumbers", false, function (cm, val) {
+ cm.display.gutterSpecs = getGutters(cm.options.gutters, val);
+ updateGutters(cm);
+ }, true);
+ option("firstLineNumber", 1, updateGutters, true);
+ option("lineNumberFormatter", function (integer) { return integer; }, updateGutters, true);
+ option("showCursorWhenSelecting", false, updateSelection, true);
+
+ option("resetSelectionOnContextMenu", true);
+ option("lineWiseCopyCut", true);
+ option("pasteLinesPerSelection", true);
+ option("selectionsMayTouch", false);
+
+ option("readOnly", false, function (cm, val) {
+ if (val == "nocursor") {
+ onBlur(cm);
+ cm.display.input.blur();
+ }
+ cm.display.input.readOnlyChanged(val);
+ });
+
+ option("screenReaderLabel", null, function (cm, val) {
+ val = (val === '') ? null : val;
+ cm.display.input.screenReaderLabelChanged(val);
+ });
+
+ option("disableInput", false, function (cm, val) {if (!val) { cm.display.input.reset(); }}, true);
+ option("dragDrop", true, dragDropChanged);
+ option("allowDropFileTypes", null);
+
+ option("cursorBlinkRate", 530);
+ option("cursorScrollMargin", 0);
+ option("cursorHeight", 1, updateSelection, true);
+ option("singleCursorHeightPerLine", true, updateSelection, true);
+ 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) { return cm.doc.history.undoDepth = val; });
+ option("historyEventDelay", 1250);
+ option("viewportMargin", 10, function (cm) { return cm.refresh(); }, true);
+ option("maxHighlightLength", 10000, resetModeState, true);
+ option("moveInputWithCursor", true, function (cm, val) {
+ if (!val) { cm.display.input.resetPosition(); }
+ });
+
+ option("tabindex", null, function (cm, val) { return cm.display.input.getField().tabIndex = val || ""; });
+ option("autofocus", null);
+ option("direction", "ltr", function (cm, val) { return cm.doc.setDirection(val); }, true);
+ option("phrases", null);
+ }
+
+ function dragDropChanged(cm, value, old) {
+ var wasOn = old && old != Init;
+ if (!value != !wasOn) {
+ var funcs = cm.display.dragFunctions;
+ var toggle = value ? on : off;
+ toggle(cm.display.scroller, "dragstart", funcs.start);
+ toggle(cm.display.scroller, "dragenter", funcs.enter);
+ toggle(cm.display.scroller, "dragover", funcs.over);
+ toggle(cm.display.scroller, "dragleave", funcs.leave);
+ toggle(cm.display.scroller, "drop", funcs.drop);
+ }
+ }
+
+ function wrappingChanged(cm) {
+ if (cm.options.lineWrapping) {
+ addClass(cm.display.wrapper, "CodeMirror-wrap");
+ cm.display.sizer.style.minWidth = "";
+ cm.display.sizerWidth = null;
+ } else {
+ rmClass(cm.display.wrapper, "CodeMirror-wrap");
+ findMaxLine(cm);
+ }
+ estimateLineHeights(cm);
+ regChange(cm);
+ clearCaches(cm);
+ setTimeout(function () { return updateScrollbars(cm); }, 100);
+ }
+
+ // A CodeMirror instance represents an editor. This is the object
+ // that user code is usually dealing with.
+
+ function CodeMirror(place, options) {
+ var this$1 = this;
+
+ if (!(this instanceof CodeMirror)) { return new CodeMirror(place, options) }
+
+ this.options = options = options ? copyObj(options) : {};
+ // Determine effective options based on given values and defaults.
+ copyObj(defaults, options, false);
+
+ var doc = options.value;
+ if (typeof doc == "string") { doc = new Doc(doc, options.mode, null, options.lineSeparator, options.direction); }
+ else if (options.mode) { doc.modeOption = options.mode; }
+ this.doc = doc;
+
+ var input = new CodeMirror.inputStyles[options.inputStyle](this);
+ var display = this.display = new Display(place, doc, input, options);
+ display.wrapper.CodeMirror = this;
+ themeChanged(this);
+ if (options.lineWrapping)
+ { this.display.wrapper.className += " CodeMirror-wrap"; }
+ initScrollbars(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,
+ delayingBlurEvent: false,
+ focused: false,
+ suppressEdits: false, // used to disable editing during key handlers when in readOnly mode
+ pasteIncoming: -1, cutIncoming: -1, // help recognize paste/cut edits in input.poll
+ selectingText: false,
+ draggingText: false,
+ highlight: new Delayed(), // stores highlight worker timeout
+ keySeq: null, // Unfinished key sequence
+ specialChars: null
+ };
+
+ if (options.autofocus && !mobile) { display.input.focus(); }
+
+ // Override magic textarea content restore that IE sometimes does
+ // on our hidden textarea on reload
+ if (ie && ie_version < 11) { setTimeout(function () { return this$1.display.input.reset(true); }, 20); }
+
+ registerEventHandlers(this);
+ ensureGlobalHandlers();
+
+ startOperation(this);
+ this.curOp.forceUpdate = true;
+ attachDoc(this, doc);
+
+ if ((options.autofocus && !mobile) || this.hasFocus())
+ { setTimeout(function () {
+ if (this$1.hasFocus() && !this$1.state.focused) { onFocus(this$1); }
+ }, 20); }
+ else
+ { onBlur(this); }
+
+ for (var opt in optionHandlers) { if (optionHandlers.hasOwnProperty(opt))
+ { optionHandlers[opt](this, options[opt], Init); } }
+ maybeUpdateLineNumberWidth(this);
+ if (options.finishInit) { options.finishInit(this); }
+ for (var i = 0; i < initHooks.length; ++i) { initHooks[i](this); }
+ endOperation(this);
+ // Suppress optimizelegibility in Webkit, since it breaks text
+ // measuring on line wrapping boundaries.
+ if (webkit && options.lineWrapping &&
+ getComputedStyle(display.lineDiv).textRendering == "optimizelegibility")
+ { display.lineDiv.style.textRendering = "auto"; }
+ }
+
+ // The default configuration options.
+ CodeMirror.defaults = defaults;
+ // Functions to run when options are changed.
+ CodeMirror.optionHandlers = optionHandlers;
+
+ // 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 && ie_version < 11)
+ { 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 = cm.findWordAt(pos);
+ extendSelection(cm.doc, word.anchor, word.head);
+ })); }
+ else
+ { on(d.scroller, "dblclick", function (e) { return signalDOMEvent(cm, 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.
+ on(d.scroller, "contextmenu", function (e) { return onContextMenu(cm, e); });
+ on(d.input.getField(), "contextmenu", function (e) {
+ if (!d.scroller.contains(e.target)) { onContextMenu(cm, e); }
+ });
+
+ // Used to suppress mouse event handling when a touch happens
+ var touchFinished, prevTouch = {end: 0};
+ function finishTouch() {
+ if (d.activeTouch) {
+ touchFinished = setTimeout(function () { return d.activeTouch = null; }, 1000);
+ prevTouch = d.activeTouch;
+ prevTouch.end = +new Date;
+ }
+ }
+ function isMouseLikeTouchEvent(e) {
+ if (e.touches.length != 1) { return false }
+ var touch = e.touches[0];
+ return touch.radiusX <= 1 && touch.radiusY <= 1
+ }
+ function farAway(touch, other) {
+ if (other.left == null) { return true }
+ var dx = other.left - touch.left, dy = other.top - touch.top;
+ return dx * dx + dy * dy > 20 * 20
+ }
+ on(d.scroller, "touchstart", function (e) {
+ if (!signalDOMEvent(cm, e) && !isMouseLikeTouchEvent(e) && !clickInGutter(cm, e)) {
+ d.input.ensurePolled();
+ clearTimeout(touchFinished);
+ var now = +new Date;
+ d.activeTouch = {start: now, moved: false,
+ prev: now - prevTouch.end <= 300 ? prevTouch : null};
+ if (e.touches.length == 1) {
+ d.activeTouch.left = e.touches[0].pageX;
+ d.activeTouch.top = e.touches[0].pageY;
+ }
+ }
+ });
+ on(d.scroller, "touchmove", function () {
+ if (d.activeTouch) { d.activeTouch.moved = true; }
+ });
+ on(d.scroller, "touchend", function (e) {
+ var touch = d.activeTouch;
+ if (touch && !eventInWidget(d, e) && touch.left != null &&
+ !touch.moved && new Date - touch.start < 300) {
+ var pos = cm.coordsChar(d.activeTouch, "page"), range;
+ if (!touch.prev || farAway(touch, touch.prev)) // Single tap
+ { range = new Range(pos, pos); }
+ else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap
+ { range = cm.findWordAt(pos); }
+ else // Triple tap
+ { range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); }
+ cm.setSelection(range.anchor, range.head);
+ cm.focus();
+ e_preventDefault(e);
+ }
+ finishTouch();
+ });
+ on(d.scroller, "touchcancel", finishTouch);
+
+ // Sync scrolling between fake scrollbars and real scrollable
+ // area, ensure viewport is updated when scrolling.
+ on(d.scroller, "scroll", function () {
+ if (d.scroller.clientHeight) {
+ updateScrollTop(cm, d.scroller.scrollTop);
+ setScrollLeft(cm, d.scroller.scrollLeft, true);
+ signal(cm, "scroll", cm);
+ }
+ });
+
+ // Listen to wheel events in order to try and update the viewport on time.
+ on(d.scroller, "mousewheel", function (e) { return onScrollWheel(cm, e); });
+ on(d.scroller, "DOMMouseScroll", function (e) { return onScrollWheel(cm, e); });
+
+ // Prevent wrapper from ever scrolling
+ on(d.wrapper, "scroll", function () { return d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; });
+
+ d.dragFunctions = {
+ enter: function (e) {if (!signalDOMEvent(cm, e)) { e_stop(e); }},
+ over: function (e) {if (!signalDOMEvent(cm, e)) { onDragOver(cm, e); e_stop(e); }},
+ start: function (e) { return onDragStart(cm, e); },
+ drop: operation(cm, onDrop),
+ leave: function (e) {if (!signalDOMEvent(cm, e)) { clearDragCursor(cm); }}
+ };
+
+ var inp = d.input.getField();
+ on(inp, "keyup", function (e) { return onKeyUp.call(cm, e); });
+ on(inp, "keydown", operation(cm, onKeyDown));
+ on(inp, "keypress", operation(cm, onKeyPress));
+ on(inp, "focus", function (e) { return onFocus(cm, e); });
+ on(inp, "blur", function (e) { return onBlur(cm, e); });
+ }
+
+ var initHooks = [];
+ CodeMirror.defineInitHook = function (f) { return initHooks.push(f); };
+
+ // 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 (!doc.mode.indent) { how = "prev"; }
+ else { state = getContextBefore(cm, n).state; }
+ }
+
+ 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 = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text);
+ if (indentation == Pass || indentation > 150) {
+ 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(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input");
+ line.stateAfter = null;
+ return true
+ } 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$1 = 0; i$1 < doc.sel.ranges.length; i$1++) {
+ var range = doc.sel.ranges[i$1];
+ if (range.head.line == n && range.head.ch < curSpaceString.length) {
+ var pos$1 = Pos(n, curSpaceString.length);
+ replaceOneSelection(doc, i$1, new Range(pos$1, pos$1));
+ break
+ }
+ }
+ }
+ }
+
+ // This will be set to a {lineWise: bool, text: [string]} object, so
+ // that, when pasting, we know what kind of selections the copied
+ // text was made out of.
+ var lastCopied = null;
+
+ function setLastCopied(newLastCopied) {
+ lastCopied = newLastCopied;
+ }
+
+ function applyTextInput(cm, inserted, deleted, sel, origin) {
+ var doc = cm.doc;
+ cm.display.shift = false;
+ if (!sel) { sel = doc.sel; }
+
+ var recent = +new Date - 200;
+ var paste = origin == "paste" || cm.state.pasteIncoming > recent;
+ var textLines = splitLinesAuto(inserted), multiPaste = null;
+ // When pasting N lines into N selections, insert one line per selection
+ if (paste && sel.ranges.length > 1) {
+ if (lastCopied && lastCopied.text.join("\n") == inserted) {
+ if (sel.ranges.length % lastCopied.text.length == 0) {
+ multiPaste = [];
+ for (var i = 0; i < lastCopied.text.length; i++)
+ { multiPaste.push(doc.splitLines(lastCopied.text[i])); }
+ }
+ } else if (textLines.length == sel.ranges.length && cm.options.pasteLinesPerSelection) {
+ multiPaste = map(textLines, function (l) { return [l]; });
+ }
+ }
+
+ var updateInput = cm.curOp.updateInput;
+ // Normal behavior is to insert the new text into every selection
+ for (var i$1 = sel.ranges.length - 1; i$1 >= 0; i$1--) {
+ var range = sel.ranges[i$1];
+ var from = range.from(), to = range.to();
+ if (range.empty()) {
+ if (deleted && deleted > 0) // Handle deletion
+ { from = Pos(from.line, from.ch - deleted); }
+ else if (cm.state.overwrite && !paste) // Handle overwrite
+ { to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); }
+ else if (paste && lastCopied && lastCopied.lineWise && lastCopied.text.join("\n") == textLines.join("\n"))
+ { from = to = Pos(from.line, 0); }
+ }
+ var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i$1 % multiPaste.length] : textLines,
+ origin: origin || (paste ? "paste" : cm.state.cutIncoming > recent ? "cut" : "+input")};
+ makeChange(cm.doc, changeEvent);
+ signalLater(cm, "inputRead", cm, changeEvent);
+ }
+ if (inserted && !paste)
+ { triggerElectric(cm, inserted); }
+
+ ensureCursorVisible(cm);
+ if (cm.curOp.updateInput < 2) { cm.curOp.updateInput = updateInput; }
+ cm.curOp.typing = true;
+ cm.state.pasteIncoming = cm.state.cutIncoming = -1;
+ }
+
+ function handlePaste(e, cm) {
+ var pasted = e.clipboardData && e.clipboardData.getData("Text");
+ if (pasted) {
+ e.preventDefault();
+ if (!cm.isReadOnly() && !cm.options.disableInput)
+ { runInOp(cm, function () { return applyTextInput(cm, pasted, 0, null, "paste"); }); }
+ return true
+ }
+ }
+
+ function triggerElectric(cm, inserted) {
+ // When an 'electric' character is inserted, immediately trigger a reindent
+ if (!cm.options.electricChars || !cm.options.smartIndent) { return }
+ var sel = cm.doc.sel;
+
+ for (var i = sel.ranges.length - 1; i >= 0; i--) {
+ var range = sel.ranges[i];
+ if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) { continue }
+ var mode = cm.getModeAt(range.head);
+ var indented = false;
+ if (mode.electricChars) {
+ for (var j = 0; j < mode.electricChars.length; j++)
+ { if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) {
+ indented = indentLine(cm, range.head.line, "smart");
+ break
+ } }
+ } else if (mode.electricInput) {
+ if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch)))
+ { indented = indentLine(cm, range.head.line, "smart"); }
+ }
+ if (indented) { signalLater(cm, "electricInput", cm, range.head.line); }
+ }
+ }
+
+ function copyableRanges(cm) {
+ var text = [], ranges = [];
+ for (var i = 0; i < cm.doc.sel.ranges.length; i++) {
+ var line = cm.doc.sel.ranges[i].head.line;
+ var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)};
+ ranges.push(lineRange);
+ text.push(cm.getRange(lineRange.anchor, lineRange.head));
+ }
+ return {text: text, ranges: ranges}
+ }
+
+ function disableBrowserMagic(field, spellcheck, autocorrect, autocapitalize) {
+ field.setAttribute("autocorrect", autocorrect ? "" : "off");
+ field.setAttribute("autocapitalize", autocapitalize ? "" : "off");
+ field.setAttribute("spellcheck", !!spellcheck);
+ }
+
+ function hiddenTextarea() {
+ var te = elt("textarea", null, null, "position: absolute; bottom: -1em; padding: 0; width: 1px; height: 1em; outline: none");
+ var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;");
+ // 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) { te.style.width = "1000px"; }
+ else { te.setAttribute("wrap", "off"); }
+ // If border: 0; -- iOS fails to open keyboard (issue #1287)
+ if (ios) { te.style.border = "1px solid black"; }
+ disableBrowserMagic(te);
+ return div
+ }
+
+ // 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.
+
+ function addEditorMethods(CodeMirror) {
+ var optionHandlers = CodeMirror.optionHandlers;
+
+ var helpers = CodeMirror.helpers = {};
+
+ CodeMirror.prototype = {
+ constructor: CodeMirror,
+ focus: function(){window.focus(); this.display.input.focus();},
+
+ 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); }
+ signal(this, "optionChange", this, option);
+ },
+
+ getOption: function(option) {return this.options[option]},
+ getDoc: function() {return this.doc},
+
+ addKeyMap: function(map, bottom) {
+ this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map));
+ },
+ removeKeyMap: function(map) {
+ var maps = this.state.keyMaps;
+ for (var i = 0; i < maps.length; ++i)
+ { if (maps[i] == map || 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.") }
+ insertSorted(this.state.overlays,
+ {mode: mode, modeSpec: spec, opaque: options && options.opaque,
+ priority: (options && options.priority) || 0},
+ function (overlay) { return overlay.priority; });
+ 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 from = range.from(), to = range.to();
+ var start = Math.max(end, from.line);
+ end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1;
+ for (var j = start; j < end; ++j)
+ { indentLine(this, j, how); }
+ var newRanges = this.doc.sel.ranges;
+ if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0)
+ { replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); }
+ } 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) {
+ return takeToken(this, pos, precise)
+ },
+
+ getLineTokens: function(line, precise) {
+ return takeToken(this, Pos(line), precise, true)
+ },
+
+ 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;
+ var type;
+ if (ch == 0) { type = styles[2]; }
+ else { 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 { type = styles[mid * 2 + 2]; break }
+ } }
+ var cut = type ? type.indexOf("overlay ") : -1;
+ return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1)
+ },
+
+ 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 found }
+ 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$1 = 0; i$1 < help._global.length; i$1++) {
+ var cur = help._global[i$1];
+ 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 getContextBefore(this, line + 1, precise).state
+ },
+
+ 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, includeWidgets) {
+ var end = false, lineObj;
+ if (typeof line == "number") {
+ var 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; }
+ lineObj = getLine(this.doc, line);
+ } else {
+ lineObj = line;
+ }
+ return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page", includeWidgets || end).top +
+ (end ? this.doc.height - heightAtLine(lineObj) : 0)
+ },
+
+ defaultTextHeight: function() { return textHeight(this.display) },
+ defaultCharWidth: function() { return charWidth(this.display) },
+
+ 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";
+ node.setAttribute("cm-ignore-events", "true");
+ this.display.input.setUneditable(node);
+ 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: left, top: top, right: left + node.offsetWidth, bottom: top + node.offsetHeight}); }
+ },
+
+ triggerOnKeyDown: methodOp(onKeyDown),
+ triggerOnKeyPress: methodOp(onKeyPress),
+ triggerOnKeyUp: onKeyUp,
+ triggerOnMouseDown: methodOp(onMouseDown),
+
+ execCommand: function(cmd) {
+ if (commands.hasOwnProperty(cmd))
+ { return commands[cmd].call(null, this) }
+ },
+
+ triggerElectric: methodOp(function(text) { triggerElectric(this, text); }),
+
+ findPosH: function(from, amount, unit, visually) {
+ var dir = 1;
+ if (amount < 0) { dir = -1; amount = -amount; }
+ var cur = clipPos(this.doc, from);
+ for (var i = 0; i < amount; ++i) {
+ cur = findPosH(this.doc, cur, dir, unit, visually);
+ if (cur.hitSide) { break }
+ }
+ return cur
+ },
+
+ moveH: methodOp(function(dir, unit) {
+ var this$1 = this;
+
+ this.extendSelectionsBy(function (range) {
+ if (this$1.display.shift || this$1.doc.extend || range.empty())
+ { return findPosH(this$1.doc, range.head, dir, unit, this$1.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; }
+ var cur = clipPos(this.doc, from);
+ for (var i = 0; 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 this$1 = this;
+
+ var doc = this.doc, goals = [];
+ var collapse = !this.display.shift && !doc.extend && doc.sel.somethingSelected();
+ doc.extendSelectionsBy(function (range) {
+ if (collapse)
+ { return dir < 0 ? range.from() : range.to() }
+ var headPos = cursorCoords(this$1, range.head, "div");
+ if (range.goalColumn != null) { headPos.left = range.goalColumn; }
+ goals.push(headPos.left);
+ var pos = findPosV(this$1, headPos, dir, unit);
+ if (unit == "page" && range == doc.sel.primary())
+ { addToScrollTop(this$1, charCoords(this$1, 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]; } }
+ }),
+
+ // Find the word at the given position (as returned by coordsChar).
+ findWordAt: function(pos) {
+ var doc = this.doc, line = getLine(doc, pos.line).text;
+ var start = pos.ch, end = pos.ch;
+ if (line) {
+ var helper = this.getHelper(pos, "wordChars");
+ if ((pos.sticky == "before" || end == line.length) && start) { --start; } else { ++end; }
+ var startChar = line.charAt(start);
+ var check = isWordChar(startChar, helper)
+ ? function (ch) { return isWordChar(ch, helper); }
+ : /\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))
+ },
+
+ toggleOverwrite: function(value) {
+ if (value != null && value == this.state.overwrite) { return }
+ if (this.state.overwrite = !this.state.overwrite)
+ { addClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
+ else
+ { rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); }
+
+ signal(this, "overwriteToggle", this, this.state.overwrite);
+ },
+ hasFocus: function() { return this.display.input.getField() == activeElt() },
+ isReadOnly: function() { return !!(this.options.readOnly || this.doc.cantEdit) },
+
+ scrollTo: methodOp(function (x, y) { scrollToCoords(this, x, y); }),
+ getScrollInfo: function() {
+ var scroller = this.display.scroller;
+ return {left: scroller.scrollLeft, top: scroller.scrollTop,
+ height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight,
+ width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth,
+ clientHeight: displayHeight(this), clientWidth: displayWidth(this)}
+ },
+
+ 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) {
+ scrollToRange(this, range);
+ } else {
+ scrollToCoordsRange(this, range.from, range.to, range.margin);
+ }
+ }),
+
+ setSize: methodOp(function(width, height) {
+ var this$1 = this;
+
+ var interpret = function (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); }
+ var lineNo = this.display.viewFrom;
+ this.doc.iter(lineNo, this.display.viewTo, function (line) {
+ if (line.widgets) { for (var i = 0; i < line.widgets.length; i++)
+ { if (line.widgets[i].noHScroll) { regLineChange(this$1, lineNo, "widget"); break } } }
+ ++lineNo;
+ });
+ this.curOp.forceUpdate = true;
+ signal(this, "refresh", this);
+ }),
+
+ operation: function(f){return runInOp(this, f)},
+ startOperation: function(){return startOperation(this)},
+ endOperation: function(){return endOperation(this)},
+
+ refresh: methodOp(function() {
+ var oldHeight = this.display.cachedTextHeight;
+ regChange(this);
+ this.curOp.forceUpdate = true;
+ clearCaches(this);
+ scrollToCoords(this, this.doc.scrollLeft, this.doc.scrollTop);
+ updateGutterSpace(this.display);
+ if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5 || this.options.lineWrapping)
+ { estimateLineHeights(this); }
+ signal(this, "refresh", this);
+ }),
+
+ swapDoc: methodOp(function(doc) {
+ var old = this.doc;
+ old.cm = null;
+ // Cancel the current text selection if any (#5821)
+ if (this.state.selectingText) { this.state.selectingText(); }
+ attachDoc(this, doc);
+ clearCaches(this);
+ this.display.input.reset();
+ scrollToCoords(this, doc.scrollLeft, doc.scrollTop);
+ this.curOp.forceScroll = true;
+ signalLater(this, "swapDoc", this, old);
+ return old
+ }),
+
+ phrase: function(phraseText) {
+ var phrases = this.options.phrases;
+ return phrases && Object.prototype.hasOwnProperty.call(phrases, phraseText) ? phrases[phraseText] : phraseText
+ },
+
+ getInputField: function(){return this.display.input.getField()},
+ getWrapperElement: function(){return this.display.wrapper},
+ getScrollerElement: function(){return this.display.scroller},
+ getGutterElement: function(){return this.display.gutters}
+ };
+ eventMixin(CodeMirror);
+
+ 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});
+ };
+ }
+
+ // Used for horizontal relative motion. Dir is -1 or 1 (left or
+ // right), unit can be "codepoint", "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 oldPos = pos;
+ var origDir = dir;
+ var lineObj = getLine(doc, pos.line);
+ var lineDir = visually && doc.direction == "rtl" ? -dir : dir;
+ function findNextLine() {
+ var l = pos.line + lineDir;
+ if (l < doc.first || l >= doc.first + doc.size) { return false }
+ pos = new Pos(l, pos.ch, pos.sticky);
+ return lineObj = getLine(doc, l)
+ }
+ function moveOnce(boundToLine) {
+ var next;
+ if (unit == "codepoint") {
+ var ch = lineObj.text.charCodeAt(pos.ch + (unit > 0 ? 0 : -1));
+ if (isNaN(ch)) { next = null; }
+ else { next = new Pos(pos.line, Math.max(0, Math.min(lineObj.text.length, pos.ch + dir * (ch >= 0xD800 && ch < 0xDC00 ? 2 : 1))),
+ -dir); }
+ } else if (visually) {
+ next = moveVisually(doc.cm, lineObj, pos, dir);
+ } else {
+ next = moveLogically(lineObj, pos, dir);
+ }
+ if (next == null) {
+ if (!boundToLine && findNextLine())
+ { pos = endOfLine(visually, doc.cm, lineObj, pos.line, lineDir); }
+ else
+ { return false }
+ } else {
+ pos = next;
+ }
+ return true
+ }
+
+ if (unit == "char" || unit == "codepoint") {
+ moveOnce();
+ } else if (unit == "column") {
+ moveOnce(true);
+ } else if (unit == "word" || unit == "group") {
+ var sawType = null, group = unit == "group";
+ var helper = doc.cm && doc.cm.getHelper(pos, "wordChars");
+ for (var first = true;; first = false) {
+ if (dir < 0 && !moveOnce(!first)) { break }
+ var cur = lineObj.text.charAt(pos.ch) || "\n";
+ var type = isWordChar(cur, helper) ? "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(); pos.sticky = "after";}
+ break
+ }
+
+ if (type) { sawType = type; }
+ if (dir > 0 && !moveOnce(!first)) { break }
+ }
+ }
+ var result = skipAtomic(doc, pos, oldPos, origDir, true);
+ if (equalCursorPos(oldPos, result)) { 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);
+ var moveAmount = Math.max(pageSize - .5 * textHeight(cm.display), 3);
+ y = (dir > 0 ? pos.bottom : pos.top) + dir * moveAmount;
+
+ } else if (unit == "line") {
+ y = dir > 0 ? pos.bottom + 3 : pos.top - 3;
+ }
+ var target;
+ for (;;) {
+ 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
+ }
+
+ // CONTENTEDITABLE INPUT STYLE
+
+ var ContentEditableInput = function(cm) {
+ this.cm = cm;
+ this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null;
+ this.polling = new Delayed();
+ this.composing = null;
+ this.gracePeriod = false;
+ this.readDOMTimeout = null;
+ };
+
+ ContentEditableInput.prototype.init = function (display) {
+ var this$1 = this;
+
+ var input = this, cm = input.cm;
+ var div = input.div = display.lineDiv;
+ disableBrowserMagic(div, cm.options.spellcheck, cm.options.autocorrect, cm.options.autocapitalize);
+
+ function belongsToInput(e) {
+ for (var t = e.target; t; t = t.parentNode) {
+ if (t == div) { return true }
+ if (/\bCodeMirror-(?:line)?widget\b/.test(t.className)) { break }
+ }
+ return false
+ }
+
+ on(div, "paste", function (e) {
+ if (!belongsToInput(e) || signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
+ // IE doesn't fire input events, so we schedule a read for the pasted content in this way
+ if (ie_version <= 11) { setTimeout(operation(cm, function () { return this$1.updateFromDOM(); }), 20); }
+ });
+
+ on(div, "compositionstart", function (e) {
+ this$1.composing = {data: e.data, done: false};
+ });
+ on(div, "compositionupdate", function (e) {
+ if (!this$1.composing) { this$1.composing = {data: e.data, done: false}; }
+ });
+ on(div, "compositionend", function (e) {
+ if (this$1.composing) {
+ if (e.data != this$1.composing.data) { this$1.readFromDOMSoon(); }
+ this$1.composing.done = true;
+ }
+ });
+
+ on(div, "touchstart", function () { return input.forceCompositionEnd(); });
+
+ on(div, "input", function () {
+ if (!this$1.composing) { this$1.readFromDOMSoon(); }
+ });
+
+ function onCopyCut(e) {
+ if (!belongsToInput(e) || signalDOMEvent(cm, e)) { return }
+ if (cm.somethingSelected()) {
+ setLastCopied({lineWise: false, text: cm.getSelections()});
+ if (e.type == "cut") { cm.replaceSelection("", null, "cut"); }
+ } else if (!cm.options.lineWiseCopyCut) {
+ return
+ } else {
+ var ranges = copyableRanges(cm);
+ setLastCopied({lineWise: true, text: ranges.text});
+ if (e.type == "cut") {
+ cm.operation(function () {
+ cm.setSelections(ranges.ranges, 0, sel_dontScroll);
+ cm.replaceSelection("", null, "cut");
+ });
+ }
+ }
+ if (e.clipboardData) {
+ e.clipboardData.clearData();
+ var content = lastCopied.text.join("\n");
+ // iOS exposes the clipboard API, but seems to discard content inserted into it
+ e.clipboardData.setData("Text", content);
+ if (e.clipboardData.getData("Text") == content) {
+ e.preventDefault();
+ return
+ }
+ }
+ // Old-fashioned briefly-focus-a-textarea hack
+ var kludge = hiddenTextarea(), te = kludge.firstChild;
+ cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild);
+ te.value = lastCopied.text.join("\n");
+ var hadFocus = document.activeElement;
+ selectInput(te);
+ setTimeout(function () {
+ cm.display.lineSpace.removeChild(kludge);
+ hadFocus.focus();
+ if (hadFocus == div) { input.showPrimarySelection(); }
+ }, 50);
+ }
+ on(div, "copy", onCopyCut);
+ on(div, "cut", onCopyCut);
+ };
+
+ ContentEditableInput.prototype.screenReaderLabelChanged = function (label) {
+ // Label for screenreaders, accessibility
+ if(label) {
+ this.div.setAttribute('aria-label', label);
+ } else {
+ this.div.removeAttribute('aria-label');
+ }
+ };
+
+ ContentEditableInput.prototype.prepareSelection = function () {
+ var result = prepareSelection(this.cm, false);
+ result.focus = document.activeElement == this.div;
+ return result
+ };
+
+ ContentEditableInput.prototype.showSelection = function (info, takeFocus) {
+ if (!info || !this.cm.display.view.length) { return }
+ if (info.focus || takeFocus) { this.showPrimarySelection(); }
+ this.showMultipleSelections(info);
+ };
+
+ ContentEditableInput.prototype.getSelection = function () {
+ return this.cm.display.wrapper.ownerDocument.getSelection()
+ };
+
+ ContentEditableInput.prototype.showPrimarySelection = function () {
+ var sel = this.getSelection(), cm = this.cm, prim = cm.doc.sel.primary();
+ var from = prim.from(), to = prim.to();
+
+ if (cm.display.viewTo == cm.display.viewFrom || from.line >= cm.display.viewTo || to.line < cm.display.viewFrom) {
+ sel.removeAllRanges();
+ return
+ }
+
+ var curAnchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
+ var curFocus = domToPos(cm, sel.focusNode, sel.focusOffset);
+ if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad &&
+ cmp(minPos(curAnchor, curFocus), from) == 0 &&
+ cmp(maxPos(curAnchor, curFocus), to) == 0)
+ { return }
+
+ var view = cm.display.view;
+ var start = (from.line >= cm.display.viewFrom && posToDOM(cm, from)) ||
+ {node: view[0].measure.map[2], offset: 0};
+ var end = to.line < cm.display.viewTo && posToDOM(cm, to);
+ if (!end) {
+ var measure = view[view.length - 1].measure;
+ var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map;
+ end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]};
+ }
+
+ if (!start || !end) {
+ sel.removeAllRanges();
+ return
+ }
+
+ var old = sel.rangeCount && sel.getRangeAt(0), rng;
+ try { rng = range(start.node, start.offset, end.offset, end.node); }
+ catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible
+ if (rng) {
+ if (!gecko && cm.state.focused) {
+ sel.collapse(start.node, start.offset);
+ if (!rng.collapsed) {
+ sel.removeAllRanges();
+ sel.addRange(rng);
+ }
+ } else {
+ sel.removeAllRanges();
+ sel.addRange(rng);
+ }
+ if (old && sel.anchorNode == null) { sel.addRange(old); }
+ else if (gecko) { this.startGracePeriod(); }
+ }
+ this.rememberSelection();
+ };
+
+ ContentEditableInput.prototype.startGracePeriod = function () {
+ var this$1 = this;
+
+ clearTimeout(this.gracePeriod);
+ this.gracePeriod = setTimeout(function () {
+ this$1.gracePeriod = false;
+ if (this$1.selectionChanged())
+ { this$1.cm.operation(function () { return this$1.cm.curOp.selectionChanged = true; }); }
+ }, 20);
+ };
+
+ ContentEditableInput.prototype.showMultipleSelections = function (info) {
+ removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors);
+ removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection);
+ };
+
+ ContentEditableInput.prototype.rememberSelection = function () {
+ var sel = this.getSelection();
+ this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset;
+ this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset;
+ };
+
+ ContentEditableInput.prototype.selectionInEditor = function () {
+ var sel = this.getSelection();
+ if (!sel.rangeCount) { return false }
+ var node = sel.getRangeAt(0).commonAncestorContainer;
+ return contains(this.div, node)
+ };
+
+ ContentEditableInput.prototype.focus = function () {
+ if (this.cm.options.readOnly != "nocursor") {
+ if (!this.selectionInEditor() || document.activeElement != this.div)
+ { this.showSelection(this.prepareSelection(), true); }
+ this.div.focus();
+ }
+ };
+ ContentEditableInput.prototype.blur = function () { this.div.blur(); };
+ ContentEditableInput.prototype.getField = function () { return this.div };
+
+ ContentEditableInput.prototype.supportsTouch = function () { return true };
+
+ ContentEditableInput.prototype.receivedFocus = function () {
+ var input = this;
+ if (this.selectionInEditor())
+ { this.pollSelection(); }
+ else
+ { runInOp(this.cm, function () { return input.cm.curOp.selectionChanged = true; }); }
+
+ function poll() {
+ if (input.cm.state.focused) {
+ input.pollSelection();
+ input.polling.set(input.cm.options.pollInterval, poll);
+ }
+ }
+ this.polling.set(this.cm.options.pollInterval, poll);
+ };
+
+ ContentEditableInput.prototype.selectionChanged = function () {
+ var sel = this.getSelection();
+ return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset ||
+ sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset
+ };
+
+ ContentEditableInput.prototype.pollSelection = function () {
+ if (this.readDOMTimeout != null || this.gracePeriod || !this.selectionChanged()) { return }
+ var sel = this.getSelection(), cm = this.cm;
+ // On Android Chrome (version 56, at least), backspacing into an
+ // uneditable block element will put the cursor in that element,
+ // and then, because it's not editable, hide the virtual keyboard.
+ // Because Android doesn't allow us to actually detect backspace
+ // presses in a sane way, this code checks for when that happens
+ // and simulates a backspace press in this case.
+ if (android && chrome && this.cm.display.gutterSpecs.length && isInGutter(sel.anchorNode)) {
+ this.cm.triggerOnKeyDown({type: "keydown", keyCode: 8, preventDefault: Math.abs});
+ this.blur();
+ this.focus();
+ return
+ }
+ if (this.composing) { return }
+ this.rememberSelection();
+ var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset);
+ var head = domToPos(cm, sel.focusNode, sel.focusOffset);
+ if (anchor && head) { runInOp(cm, function () {
+ setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll);
+ if (anchor.bad || head.bad) { cm.curOp.selectionChanged = true; }
+ }); }
+ };
+
+ ContentEditableInput.prototype.pollContent = function () {
+ if (this.readDOMTimeout != null) {
+ clearTimeout(this.readDOMTimeout);
+ this.readDOMTimeout = null;
+ }
+
+ var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary();
+ var from = sel.from(), to = sel.to();
+ if (from.ch == 0 && from.line > cm.firstLine())
+ { from = Pos(from.line - 1, getLine(cm.doc, from.line - 1).length); }
+ if (to.ch == getLine(cm.doc, to.line).text.length && to.line < cm.lastLine())
+ { to = Pos(to.line + 1, 0); }
+ if (from.line < display.viewFrom || to.line > display.viewTo - 1) { return false }
+
+ var fromIndex, fromLine, fromNode;
+ if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) {
+ fromLine = lineNo(display.view[0].line);
+ fromNode = display.view[0].node;
+ } else {
+ fromLine = lineNo(display.view[fromIndex].line);
+ fromNode = display.view[fromIndex - 1].node.nextSibling;
+ }
+ var toIndex = findViewIndex(cm, to.line);
+ var toLine, toNode;
+ if (toIndex == display.view.length - 1) {
+ toLine = display.viewTo - 1;
+ toNode = display.lineDiv.lastChild;
+ } else {
+ toLine = lineNo(display.view[toIndex + 1].line) - 1;
+ toNode = display.view[toIndex + 1].node.previousSibling;
+ }
+
+ if (!fromNode) { return false }
+ var newText = cm.doc.splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine));
+ var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length));
+ while (newText.length > 1 && oldText.length > 1) {
+ if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; }
+ else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; }
+ else { break }
+ }
+
+ var cutFront = 0, cutEnd = 0;
+ var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length);
+ while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront))
+ { ++cutFront; }
+ var newBot = lst(newText), oldBot = lst(oldText);
+ var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0),
+ oldBot.length - (oldText.length == 1 ? cutFront : 0));
+ while (cutEnd < maxCutEnd &&
+ newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1))
+ { ++cutEnd; }
+ // Try to move start of change to start of selection if ambiguous
+ if (newText.length == 1 && oldText.length == 1 && fromLine == from.line) {
+ while (cutFront && cutFront > from.ch &&
+ newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {
+ cutFront--;
+ cutEnd++;
+ }
+ }
+
+ newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd).replace(/^\u200b+/, "");
+ newText[0] = newText[0].slice(cutFront).replace(/\u200b+$/, "");
+
+ var chFrom = Pos(fromLine, cutFront);
+ var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0);
+ if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) {
+ replaceRange(cm.doc, newText, chFrom, chTo, "+input");
+ return true
+ }
+ };
+
+ ContentEditableInput.prototype.ensurePolled = function () {
+ this.forceCompositionEnd();
+ };
+ ContentEditableInput.prototype.reset = function () {
+ this.forceCompositionEnd();
+ };
+ ContentEditableInput.prototype.forceCompositionEnd = function () {
+ if (!this.composing) { return }
+ clearTimeout(this.readDOMTimeout);
+ this.composing = null;
+ this.updateFromDOM();
+ this.div.blur();
+ this.div.focus();
+ };
+ ContentEditableInput.prototype.readFromDOMSoon = function () {
+ var this$1 = this;
+
+ if (this.readDOMTimeout != null) { return }
+ this.readDOMTimeout = setTimeout(function () {
+ this$1.readDOMTimeout = null;
+ if (this$1.composing) {
+ if (this$1.composing.done) { this$1.composing = null; }
+ else { return }
+ }
+ this$1.updateFromDOM();
+ }, 80);
+ };
+
+ ContentEditableInput.prototype.updateFromDOM = function () {
+ var this$1 = this;
+
+ if (this.cm.isReadOnly() || !this.pollContent())
+ { runInOp(this.cm, function () { return regChange(this$1.cm); }); }
+ };
+
+ ContentEditableInput.prototype.setUneditable = function (node) {
+ node.contentEditable = "false";
+ };
+
+ ContentEditableInput.prototype.onKeyPress = function (e) {
+ if (e.charCode == 0 || this.composing) { return }
+ e.preventDefault();
+ if (!this.cm.isReadOnly())
+ { operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); }
+ };
+
+ ContentEditableInput.prototype.readOnlyChanged = function (val) {
+ this.div.contentEditable = String(val != "nocursor");
+ };
+
+ ContentEditableInput.prototype.onContextMenu = function () {};
+ ContentEditableInput.prototype.resetPosition = function () {};
+
+ ContentEditableInput.prototype.needsContentAttribute = true;
+
+ function posToDOM(cm, pos) {
+ var view = findViewForLine(cm, pos.line);
+ if (!view || view.hidden) { return null }
+ var line = getLine(cm.doc, pos.line);
+ var info = mapFromLineView(view, line, pos.line);
+
+ var order = getOrder(line, cm.doc.direction), side = "left";
+ if (order) {
+ var partPos = getBidiPartAt(order, pos.ch);
+ side = partPos % 2 ? "right" : "left";
+ }
+ var result = nodeAndOffsetInLineMap(info.map, pos.ch, side);
+ result.offset = result.collapse == "right" ? result.end : result.start;
+ return result
+ }
+
+ function isInGutter(node) {
+ for (var scan = node; scan; scan = scan.parentNode)
+ { if (/CodeMirror-gutter-wrapper/.test(scan.className)) { return true } }
+ return false
+ }
+
+ function badPos(pos, bad) { if (bad) { pos.bad = true; } return pos }
+
+ function domTextBetween(cm, from, to, fromLine, toLine) {
+ var text = "", closing = false, lineSep = cm.doc.lineSeparator(), extraLinebreak = false;
+ function recognizeMarker(id) { return function (marker) { return marker.id == id; } }
+ function close() {
+ if (closing) {
+ text += lineSep;
+ if (extraLinebreak) { text += lineSep; }
+ closing = extraLinebreak = false;
+ }
+ }
+ function addText(str) {
+ if (str) {
+ close();
+ text += str;
+ }
+ }
+ function walk(node) {
+ if (node.nodeType == 1) {
+ var cmText = node.getAttribute("cm-text");
+ if (cmText) {
+ addText(cmText);
+ return
+ }
+ var markerID = node.getAttribute("cm-marker"), range;
+ if (markerID) {
+ var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID));
+ if (found.length && (range = found[0].find(0)))
+ { addText(getBetween(cm.doc, range.from, range.to).join(lineSep)); }
+ return
+ }
+ if (node.getAttribute("contenteditable") == "false") { return }
+ var isBlock = /^(pre|div|p|li|table|br)$/i.test(node.nodeName);
+ if (!/^br$/i.test(node.nodeName) && node.textContent.length == 0) { return }
+
+ if (isBlock) { close(); }
+ for (var i = 0; i < node.childNodes.length; i++)
+ { walk(node.childNodes[i]); }
+
+ if (/^(pre|p)$/i.test(node.nodeName)) { extraLinebreak = true; }
+ if (isBlock) { closing = true; }
+ } else if (node.nodeType == 3) {
+ addText(node.nodeValue.replace(/\u200b/g, "").replace(/\u00a0/g, " "));
+ }
+ }
+ for (;;) {
+ walk(from);
+ if (from == to) { break }
+ from = from.nextSibling;
+ extraLinebreak = false;
+ }
+ return text
+ }
+
+ function domToPos(cm, node, offset) {
+ var lineNode;
+ if (node == cm.display.lineDiv) {
+ lineNode = cm.display.lineDiv.childNodes[offset];
+ if (!lineNode) { return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true) }
+ node = null; offset = 0;
+ } else {
+ for (lineNode = node;; lineNode = lineNode.parentNode) {
+ if (!lineNode || lineNode == cm.display.lineDiv) { return null }
+ if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) { break }
+ }
+ }
+ for (var i = 0; i < cm.display.view.length; i++) {
+ var lineView = cm.display.view[i];
+ if (lineView.node == lineNode)
+ { return locateNodeInLineView(lineView, node, offset) }
+ }
+ }
+
+ function locateNodeInLineView(lineView, node, offset) {
+ var wrapper = lineView.text.firstChild, bad = false;
+ if (!node || !contains(wrapper, node)) { return badPos(Pos(lineNo(lineView.line), 0), true) }
+ if (node == wrapper) {
+ bad = true;
+ node = wrapper.childNodes[offset];
+ offset = 0;
+ if (!node) {
+ var line = lineView.rest ? lst(lineView.rest) : lineView.line;
+ return badPos(Pos(lineNo(line), line.text.length), bad)
+ }
+ }
+
+ var textNode = node.nodeType == 3 ? node : null, topNode = node;
+ if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) {
+ textNode = node.firstChild;
+ if (offset) { offset = textNode.nodeValue.length; }
+ }
+ while (topNode.parentNode != wrapper) { topNode = topNode.parentNode; }
+ var measure = lineView.measure, maps = measure.maps;
+
+ function find(textNode, topNode, offset) {
+ for (var i = -1; i < (maps ? maps.length : 0); i++) {
+ var map = i < 0 ? measure.map : maps[i];
+ for (var j = 0; j < map.length; j += 3) {
+ var curNode = map[j + 2];
+ if (curNode == textNode || curNode == topNode) {
+ var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]);
+ var ch = map[j] + offset;
+ if (offset < 0 || curNode != textNode) { ch = map[j + (offset ? 1 : 0)]; }
+ return Pos(line, ch)
+ }
+ }
+ }
+ }
+ var found = find(textNode, topNode, offset);
+ if (found) { return badPos(found, bad) }
+
+ // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems
+ for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) {
+ found = find(after, after.firstChild, 0);
+ if (found)
+ { return badPos(Pos(found.line, found.ch - dist), bad) }
+ else
+ { dist += after.textContent.length; }
+ }
+ for (var before = topNode.previousSibling, dist$1 = offset; before; before = before.previousSibling) {
+ found = find(before, before.firstChild, -1);
+ if (found)
+ { return badPos(Pos(found.line, found.ch + dist$1), bad) }
+ else
+ { dist$1 += before.textContent.length; }
+ }
+ }
+
+ // TEXTAREA INPUT STYLE
+
+ var TextareaInput = function(cm) {
+ this.cm = cm;
+ // See input.poll and input.reset
+ this.prevInput = "";
+
+ // Flag that indicates whether we expect input to appear real soon
+ // now (after some event like 'keypress' or 'input') and are
+ // polling intensively.
+ this.pollingFast = false;
+ // Self-resetting timeout for the poller
+ this.polling = new Delayed();
+ // Used to work around IE issue with selection being forgotten when focus moves away from textarea
+ this.hasSelection = false;
+ this.composing = null;
+ };
+
+ TextareaInput.prototype.init = function (display) {
+ var this$1 = this;
+
+ var input = this, cm = this.cm;
+ this.createField(display);
+ var te = this.textarea;
+
+ display.wrapper.insertBefore(this.wrapper, display.wrapper.firstChild);
+
+ // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore)
+ if (ios) { te.style.width = "0px"; }
+
+ on(te, "input", function () {
+ if (ie && ie_version >= 9 && this$1.hasSelection) { this$1.hasSelection = null; }
+ input.poll();
+ });
+
+ on(te, "paste", function (e) {
+ if (signalDOMEvent(cm, e) || handlePaste(e, cm)) { return }
+
+ cm.state.pasteIncoming = +new Date;
+ input.fastPoll();
+ });
+
+ function prepareCopyCut(e) {
+ if (signalDOMEvent(cm, e)) { return }
+ if (cm.somethingSelected()) {
+ setLastCopied({lineWise: false, text: cm.getSelections()});
+ } else if (!cm.options.lineWiseCopyCut) {
+ return
+ } else {
+ var ranges = copyableRanges(cm);
+ setLastCopied({lineWise: true, text: ranges.text});
+ if (e.type == "cut") {
+ cm.setSelections(ranges.ranges, null, sel_dontScroll);
+ } else {
+ input.prevInput = "";
+ te.value = ranges.text.join("\n");
+ selectInput(te);
+ }
+ }
+ if (e.type == "cut") { cm.state.cutIncoming = +new Date; }
+ }
+ on(te, "cut", prepareCopyCut);
+ on(te, "copy", prepareCopyCut);
+
+ on(display.scroller, "paste", function (e) {
+ if (eventInWidget(display, e) || signalDOMEvent(cm, e)) { return }
+ if (!te.dispatchEvent) {
+ cm.state.pasteIncoming = +new Date;
+ input.focus();
+ return
+ }
+
+ // Pass the `paste` event to the textarea so it's handled by its event listener.
+ var event = new Event("paste");
+ event.clipboardData = e.clipboardData;
+ te.dispatchEvent(event);
+ });
+
+ // Prevent normal selection in the editor (we handle our own)
+ on(display.lineSpace, "selectstart", function (e) {
+ if (!eventInWidget(display, e)) { e_preventDefault(e); }
+ });
+
+ on(te, "compositionstart", function () {
+ var start = cm.getCursor("from");
+ if (input.composing) { input.composing.range.clear(); }
+ input.composing = {
+ start: start,
+ range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"})
+ };
+ });
+ on(te, "compositionend", function () {
+ if (input.composing) {
+ input.poll();
+ input.composing.range.clear();
+ input.composing = null;
+ }
+ });
+ };
+
+ TextareaInput.prototype.createField = function (_display) {
+ // Wraps and hides input textarea
+ this.wrapper = hiddenTextarea();
+ // The semihidden textarea that is focused when the editor is
+ // focused, and receives input.
+ this.textarea = this.wrapper.firstChild;
+ };
+
+ TextareaInput.prototype.screenReaderLabelChanged = function (label) {
+ // Label for screenreaders, accessibility
+ if(label) {
+ this.textarea.setAttribute('aria-label', label);
+ } else {
+ this.textarea.removeAttribute('aria-label');
+ }
+ };
+
+ TextareaInput.prototype.prepareSelection = function () {
+ // Redraw the selection and/or cursor
+ var cm = this.cm, display = cm.display, doc = cm.doc;
+ var result = prepareSelection(cm);
+
+ // 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();
+ result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10,
+ headPos.top + lineOff.top - wrapOff.top));
+ result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10,
+ headPos.left + lineOff.left - wrapOff.left));
+ }
+
+ return result
+ };
+
+ TextareaInput.prototype.showSelection = function (drawn) {
+ var cm = this.cm, display = cm.display;
+ removeChildrenAndAdd(display.cursorDiv, drawn.cursors);
+ removeChildrenAndAdd(display.selectionDiv, drawn.selection);
+ if (drawn.teTop != null) {
+ this.wrapper.style.top = drawn.teTop + "px";
+ this.wrapper.style.left = drawn.teLeft + "px";
+ }
+ };
+
+ // Reset the input to correspond to the selection (or to be empty,
+ // when not typing and nothing is selected)
+ TextareaInput.prototype.reset = function (typing) {
+ if (this.contextMenuPending || this.composing) { return }
+ var cm = this.cm;
+ if (cm.somethingSelected()) {
+ this.prevInput = "";
+ var content = cm.getSelection();
+ this.textarea.value = content;
+ if (cm.state.focused) { selectInput(this.textarea); }
+ if (ie && ie_version >= 9) { this.hasSelection = content; }
+ } else if (!typing) {
+ this.prevInput = this.textarea.value = "";
+ if (ie && ie_version >= 9) { this.hasSelection = null; }
+ }
+ };
+
+ TextareaInput.prototype.getField = function () { return this.textarea };
+
+ TextareaInput.prototype.supportsTouch = function () { return false };
+
+ TextareaInput.prototype.focus = function () {
+ if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) {
+ try { this.textarea.focus(); }
+ catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM
+ }
+ };
+
+ TextareaInput.prototype.blur = function () { this.textarea.blur(); };
+
+ TextareaInput.prototype.resetPosition = function () {
+ this.wrapper.style.top = this.wrapper.style.left = 0;
+ };
+
+ TextareaInput.prototype.receivedFocus = function () { this.slowPoll(); };
+
+ // Poll for input changes, using the normal rate of polling. This
+ // runs as long as the editor is focused.
+ TextareaInput.prototype.slowPoll = function () {
+ var this$1 = this;
+
+ if (this.pollingFast) { return }
+ this.polling.set(this.cm.options.pollInterval, function () {
+ this$1.poll();
+ if (this$1.cm.state.focused) { this$1.slowPoll(); }
+ });
+ };
+
+ // 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.
+ TextareaInput.prototype.fastPoll = function () {
+ var missed = false, input = this;
+ input.pollingFast = true;
+ function p() {
+ var changed = input.poll();
+ if (!changed && !missed) {missed = true; input.polling.set(60, p);}
+ else {input.pollingFast = false; input.slowPoll();}
+ }
+ input.polling.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).
+ TextareaInput.prototype.poll = function () {
+ var this$1 = this;
+
+ var cm = this.cm, input = this.textarea, prevInput = this.prevInput;
+ // 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 (this.contextMenuPending || !cm.state.focused ||
+ (hasSelection(input) && !prevInput && !this.composing) ||
+ cm.isReadOnly() || cm.options.disableInput || cm.state.keySeq)
+ { 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, and
+ // inexplicable appearance of private area unicode characters on
+ // some key combos in Mac (#2689).
+ if (ie && ie_version >= 9 && this.hasSelection === text ||
+ mac && /[\uf700-\uf7ff]/.test(text)) {
+ cm.display.input.reset();
+ return false
+ }
+
+ if (cm.doc.sel == cm.display.selForContextMenu) {
+ var first = text.charCodeAt(0);
+ if (first == 0x200b && !prevInput) { prevInput = "\u200b"; }
+ if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo") }
+ }
+ // 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; }
+
+ runInOp(cm, function () {
+ applyTextInput(cm, text.slice(same), prevInput.length - same,
+ null, this$1.composing ? "*compose" : null);
+
+ // Don't leave long text in the textarea, since it makes further polling slow
+ if (text.length > 1000 || text.indexOf("\n") > -1) { input.value = this$1.prevInput = ""; }
+ else { this$1.prevInput = text; }
+
+ if (this$1.composing) {
+ this$1.composing.range.clear();
+ this$1.composing.range = cm.markText(this$1.composing.start, cm.getCursor("to"),
+ {className: "CodeMirror-composing"});
+ }
+ });
+ return true
+ };
+
+ TextareaInput.prototype.ensurePolled = function () {
+ if (this.pollingFast && this.poll()) { this.pollingFast = false; }
+ };
+
+ TextareaInput.prototype.onKeyPress = function () {
+ if (ie && ie_version >= 9) { this.hasSelection = null; }
+ this.fastPoll();
+ };
+
+ TextareaInput.prototype.onContextMenu = function (e) {
+ var input = this, cm = input.cm, display = cm.display, te = input.textarea;
+ if (input.contextMenuPending) { input.contextMenuPending(); }
+ 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 = te.style.cssText, oldWrapperCSS = input.wrapper.style.cssText;
+ var wrapperBox = input.wrapper.offsetParent.getBoundingClientRect();
+ input.wrapper.style.cssText = "position: static";
+ te.style.cssText = "position: absolute; width: 30px; height: 30px;\n top: " + (e.clientY - wrapperBox.top - 5) + "px; left: " + (e.clientX - wrapperBox.left - 5) + "px;\n z-index: 1000; background: " + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + ";\n outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";
+ var oldScrollY;
+ if (webkit) { oldScrollY = window.scrollY; } // Work around Chrome issue (#2712)
+ display.input.focus();
+ if (webkit) { window.scrollTo(null, oldScrollY); }
+ display.input.reset();
+ // Adds "Select all" to context menu in FF
+ if (!cm.somethingSelected()) { te.value = input.prevInput = " "; }
+ input.contextMenuPending = rehide;
+ display.selForContextMenu = cm.doc.sel;
+ clearTimeout(display.detectingSelectAll);
+
+ // 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 (te.selectionStart != null) {
+ var selected = cm.somethingSelected();
+ var extval = "\u200b" + (selected ? te.value : "");
+ te.value = "\u21da"; // Used to catch context-menu undo
+ te.value = extval;
+ input.prevInput = selected ? "" : "\u200b";
+ te.selectionStart = 1; te.selectionEnd = extval.length;
+ // Re-set this, in case some other handler touched the
+ // selection in the meantime.
+ display.selForContextMenu = cm.doc.sel;
+ }
+ }
+ function rehide() {
+ if (input.contextMenuPending != rehide) { return }
+ input.contextMenuPending = false;
+ input.wrapper.style.cssText = oldWrapperCSS;
+ te.style.cssText = oldCSS;
+ if (ie && ie_version < 9) { display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); }
+
+ // Try to detect the user choosing select-all
+ if (te.selectionStart != null) {
+ if (!ie || (ie && ie_version < 9)) { prepareSelectAllHack(); }
+ var i = 0, poll = function () {
+ if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 &&
+ te.selectionEnd > 0 && input.prevInput == "\u200b") {
+ operation(cm, selectAll)(cm);
+ } else if (i++ < 10) {
+ display.detectingSelectAll = setTimeout(poll, 500);
+ } else {
+ display.selForContextMenu = null;
+ display.input.reset();
+ }
+ };
+ display.detectingSelectAll = setTimeout(poll, 200);
+ }
+ }
+
+ if (ie && ie_version >= 9) { prepareSelectAllHack(); }
+ if (captureRightClick) {
+ e_stop(e);
+ var mouseup = function () {
+ off(window, "mouseup", mouseup);
+ setTimeout(rehide, 20);
+ };
+ on(window, "mouseup", mouseup);
+ } else {
+ setTimeout(rehide, 50);
+ }
+ };
+
+ TextareaInput.prototype.readOnlyChanged = function (val) {
+ if (!val) { this.reset(); }
+ this.textarea.disabled = val == "nocursor";
+ this.textarea.readOnly = !!val;
+ };
+
+ TextareaInput.prototype.setUneditable = function () {};
+
+ TextareaInput.prototype.needsContentAttribute = false;
+
+ function fromTextArea(textarea, options) {
+ options = options ? copyObj(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();}
+
+ var realSubmit;
+ 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) {}
+ }
+ }
+
+ options.finishInit = function (cm) {
+ cm.save = save;
+ cm.getTextArea = function () { return textarea; };
+ cm.toTextArea = function () {
+ cm.toTextArea = isNaN; // Prevent this from being ran twice
+ save();
+ textarea.parentNode.removeChild(cm.getWrapperElement());
+ textarea.style.display = "";
+ if (textarea.form) {
+ off(textarea.form, "submit", save);
+ if (!options.leaveSubmitMethodAlone && typeof textarea.form.submit == "function")
+ { textarea.form.submit = realSubmit; }
+ }
+ };
+ };
+
+ textarea.style.display = "none";
+ var cm = CodeMirror(function (node) { return textarea.parentNode.insertBefore(node, textarea.nextSibling); },
+ options);
+ return cm
+ }
+
+ function addLegacyProps(CodeMirror) {
+ CodeMirror.off = off;
+ CodeMirror.on = on;
+ CodeMirror.wheelEventPixels = wheelEventPixels;
+ CodeMirror.Doc = Doc;
+ CodeMirror.splitLines = splitLinesAuto;
+ CodeMirror.countColumn = countColumn;
+ CodeMirror.findColumn = findColumn;
+ CodeMirror.isWordChar = isWordCharBasic;
+ CodeMirror.Pass = Pass;
+ CodeMirror.signal = signal;
+ CodeMirror.Line = Line;
+ CodeMirror.changeEnd = changeEnd;
+ CodeMirror.scrollbarModel = scrollbarModel;
+ CodeMirror.Pos = Pos;
+ CodeMirror.cmpPos = cmp;
+ CodeMirror.modes = modes;
+ CodeMirror.mimeModes = mimeModes;
+ CodeMirror.resolveMode = resolveMode;
+ CodeMirror.getMode = getMode;
+ CodeMirror.modeExtensions = modeExtensions;
+ CodeMirror.extendMode = extendMode;
+ CodeMirror.copyState = copyState;
+ CodeMirror.startState = startState;
+ CodeMirror.innerMode = innerMode;
+ CodeMirror.commands = commands;
+ CodeMirror.keyMap = keyMap;
+ CodeMirror.keyName = keyName;
+ CodeMirror.isModifierKey = isModifierKey;
+ CodeMirror.lookupKey = lookupKey;
+ CodeMirror.normalizeKeyMap = normalizeKeyMap;
+ CodeMirror.StringStream = StringStream;
+ CodeMirror.SharedTextMarker = SharedTextMarker;
+ CodeMirror.TextMarker = TextMarker;
+ CodeMirror.LineWidget = LineWidget;
+ CodeMirror.e_preventDefault = e_preventDefault;
+ CodeMirror.e_stopPropagation = e_stopPropagation;
+ CodeMirror.e_stop = e_stop;
+ CodeMirror.addClass = addClass;
+ CodeMirror.contains = contains;
+ CodeMirror.rmClass = rmClass;
+ CodeMirror.keyNames = keyNames;
+ }
+
+ // EDITOR CONSTRUCTOR
+
+ defineOptions(CodeMirror);
+
+ addEditorMethods(CodeMirror);
+
+ // Set up methods on CodeMirror's prototype to redirect to the editor's document.
+ var dontDelegate = "iter insert remove copy getEditor constructor".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);
+ CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput};
+
+ // 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; }
+ defineMode.apply(this, arguments);
+ };
+
+ CodeMirror.defineMIME = defineMIME;
+
+ // Minimal default mode.
+ CodeMirror.defineMode("null", function () { return ({token: function (stream) { return stream.skipToEnd(); }}); });
+ CodeMirror.defineMIME("text/plain", "null");
+
+ // EXTENSIONS
+
+ CodeMirror.defineExtension = function (name, func) {
+ CodeMirror.prototype[name] = func;
+ };
+ CodeMirror.defineDocExtension = function (name, func) {
+ Doc.prototype[name] = func;
+ };
+
+ CodeMirror.fromTextArea = fromTextArea;
+
+ addLegacyProps(CodeMirror);
+
+ CodeMirror.version = "5.58.1";
+
+ return CodeMirror;
+
+})));
diff --git a/devtools/client/shared/sourceeditor/codemirror/mode/clike/clike.js b/devtools/client/shared/sourceeditor/codemirror/mode/clike/clike.js
new file mode 100644
index 0000000000..b3f099149f
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/mode/clike/clike.js
@@ -0,0 +1,889 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+"use strict";
+
+function Context(indented, column, type, info, align, prev) {
+ this.indented = indented;
+ this.column = column;
+ this.type = type;
+ this.info = info;
+ this.align = align;
+ this.prev = prev;
+}
+function pushContext(state, col, type, info) {
+ var indent = state.indented;
+ if (state.context && state.context.type == "statement" && type != "statement")
+ indent = state.context.indented;
+ return state.context = new Context(indent, col, type, info, null, state.context);
+}
+function popContext(state) {
+ var t = state.context.type;
+ if (t == ")" || t == "]" || t == "}")
+ state.indented = state.context.indented;
+ return state.context = state.context.prev;
+}
+
+function typeBefore(stream, state, pos) {
+ if (state.prevToken == "variable" || state.prevToken == "type") return true;
+ if (/\S(?:[^- ]>|[*\]])\s*$|\*$/.test(stream.string.slice(0, pos))) return true;
+ if (state.typeAtEndOfLine && stream.column() == stream.indentation()) return true;
+}
+
+function isTopScope(context) {
+ for (;;) {
+ if (!context || context.type == "top") return true;
+ if (context.type == "}" && context.prev.info != "namespace") return false;
+ context = context.prev;
+ }
+}
+
+CodeMirror.defineMode("clike", function(config, parserConfig) {
+ var indentUnit = config.indentUnit,
+ statementIndentUnit = parserConfig.statementIndentUnit || indentUnit,
+ dontAlignCalls = parserConfig.dontAlignCalls,
+ keywords = parserConfig.keywords || {},
+ types = parserConfig.types || {},
+ builtin = parserConfig.builtin || {},
+ blockKeywords = parserConfig.blockKeywords || {},
+ defKeywords = parserConfig.defKeywords || {},
+ atoms = parserConfig.atoms || {},
+ hooks = parserConfig.hooks || {},
+ multiLineStrings = parserConfig.multiLineStrings,
+ indentStatements = parserConfig.indentStatements !== false,
+ indentSwitch = parserConfig.indentSwitch !== false,
+ namespaceSeparator = parserConfig.namespaceSeparator,
+ isPunctuationChar = parserConfig.isPunctuationChar || /[\[\]{}\(\),;\:\.]/,
+ numberStart = parserConfig.numberStart || /[\d\.]/,
+ number = parserConfig.number || /^(?:0x[a-f\d]+|0b[01]+|(?:\d+\.?\d*|\.\d+)(?:e[-+]?\d+)?)(u|ll?|l|f)?/i,
+ isOperatorChar = parserConfig.isOperatorChar || /[+\-*&%=<>!?|\/]/,
+ isIdentifierChar = parserConfig.isIdentifierChar || /[\w\$_\xa1-\uffff]/,
+ // An optional function that takes a {string} token and returns true if it
+ // should be treated as a builtin.
+ isReservedIdentifier = parserConfig.isReservedIdentifier || false;
+
+ var curPunc, isDefKeyword;
+
+ function tokenBase(stream, state) {
+ var ch = stream.next();
+ if (hooks[ch]) {
+ var result = hooks[ch](stream, state);
+ if (result !== false) return result;
+ }
+ if (ch == '"' || ch == "'") {
+ state.tokenize = tokenString(ch);
+ return state.tokenize(stream, state);
+ }
+ if (isPunctuationChar.test(ch)) {
+ curPunc = ch;
+ return null;
+ }
+ if (numberStart.test(ch)) {
+ stream.backUp(1)
+ if (stream.match(number)) return "number"
+ stream.next()
+ }
+ if (ch == "/") {
+ if (stream.eat("*")) {
+ state.tokenize = tokenComment;
+ return tokenComment(stream, state);
+ }
+ if (stream.eat("/")) {
+ stream.skipToEnd();
+ return "comment";
+ }
+ }
+ if (isOperatorChar.test(ch)) {
+ while (!stream.match(/^\/[\/*]/, false) && stream.eat(isOperatorChar)) {}
+ return "operator";
+ }
+ stream.eatWhile(isIdentifierChar);
+ if (namespaceSeparator) while (stream.match(namespaceSeparator))
+ stream.eatWhile(isIdentifierChar);
+
+ var cur = stream.current();
+ if (contains(keywords, cur)) {
+ if (contains(blockKeywords, cur)) curPunc = "newstatement";
+ if (contains(defKeywords, cur)) isDefKeyword = true;
+ return "keyword";
+ }
+ if (contains(types, cur)) return "type";
+ if (contains(builtin, cur)
+ || (isReservedIdentifier && isReservedIdentifier(cur))) {
+ if (contains(blockKeywords, cur)) curPunc = "newstatement";
+ return "builtin";
+ }
+ if (contains(atoms, cur)) return "atom";
+ return "variable";
+ }
+
+ function tokenString(quote) {
+ return function(stream, state) {
+ var escaped = false, next, end = false;
+ while ((next = stream.next()) != null) {
+ if (next == quote && !escaped) {end = true; break;}
+ escaped = !escaped && next == "\\";
+ }
+ if (end || !(escaped || multiLineStrings))
+ state.tokenize = null;
+ return "string";
+ };
+ }
+
+ function tokenComment(stream, state) {
+ var maybeEnd = false, ch;
+ while (ch = stream.next()) {
+ if (ch == "/" && maybeEnd) {
+ state.tokenize = null;
+ break;
+ }
+ maybeEnd = (ch == "*");
+ }
+ return "comment";
+ }
+
+ function maybeEOL(stream, state) {
+ if (parserConfig.typeFirstDefinitions && stream.eol() && isTopScope(state.context))
+ state.typeAtEndOfLine = typeBefore(stream, state, stream.pos)
+ }
+
+ // Interface
+
+ return {
+ startState: function(basecolumn) {
+ return {
+ tokenize: null,
+ context: new Context((basecolumn || 0) - indentUnit, 0, "top", null, false),
+ indented: 0,
+ startOfLine: true,
+ prevToken: null
+ };
+ },
+
+ token: function(stream, state) {
+ var ctx = state.context;
+ if (stream.sol()) {
+ if (ctx.align == null) ctx.align = false;
+ state.indented = stream.indentation();
+ state.startOfLine = true;
+ }
+ if (stream.eatSpace()) { maybeEOL(stream, state); return null; }
+ curPunc = isDefKeyword = null;
+ var style = (state.tokenize || tokenBase)(stream, state);
+ if (style == "comment" || style == "meta") return style;
+ if (ctx.align == null) ctx.align = true;
+
+ if (curPunc == ";" || curPunc == ":" || (curPunc == "," && stream.match(/^\s*(?:\/\/.*)?$/, false)))
+ while (state.context.type == "statement") popContext(state);
+ else if (curPunc == "{") pushContext(state, stream.column(), "}");
+ else if (curPunc == "[") pushContext(state, stream.column(), "]");
+ else if (curPunc == "(") pushContext(state, stream.column(), ")");
+ else if (curPunc == "}") {
+ while (ctx.type == "statement") ctx = popContext(state);
+ if (ctx.type == "}") ctx = popContext(state);
+ while (ctx.type == "statement") ctx = popContext(state);
+ }
+ else if (curPunc == ctx.type) popContext(state);
+ else if (indentStatements &&
+ (((ctx.type == "}" || ctx.type == "top") && curPunc != ";") ||
+ (ctx.type == "statement" && curPunc == "newstatement"))) {
+ pushContext(state, stream.column(), "statement", stream.current());
+ }
+
+ if (style == "variable" &&
+ ((state.prevToken == "def" ||
+ (parserConfig.typeFirstDefinitions && typeBefore(stream, state, stream.start) &&
+ isTopScope(state.context) && stream.match(/^\s*\(/, false)))))
+ style = "def";
+
+ if (hooks.token) {
+ var result = hooks.token(stream, state, style);
+ if (result !== undefined) style = result;
+ }
+
+ if (style == "def" && parserConfig.styleDefs === false) style = "variable";
+
+ state.startOfLine = false;
+ state.prevToken = isDefKeyword ? "def" : style || curPunc;
+ maybeEOL(stream, state);
+ return style;
+ },
+
+ indent: function(state, textAfter) {
+ if (state.tokenize != tokenBase && state.tokenize != null || state.typeAtEndOfLine) return CodeMirror.Pass;
+ var ctx = state.context, firstChar = textAfter && textAfter.charAt(0);
+ var closing = firstChar == ctx.type;
+ if (ctx.type == "statement" && firstChar == "}") ctx = ctx.prev;
+ if (parserConfig.dontIndentStatements)
+ while (ctx.type == "statement" && parserConfig.dontIndentStatements.test(ctx.info))
+ ctx = ctx.prev
+ if (hooks.indent) {
+ var hook = hooks.indent(state, ctx, textAfter, indentUnit);
+ if (typeof hook == "number") return hook
+ }
+ var switchBlock = ctx.prev && ctx.prev.info == "switch";
+ if (parserConfig.allmanIndentation && /[{(]/.test(firstChar)) {
+ while (ctx.type != "top" && ctx.type != "}") ctx = ctx.prev
+ return ctx.indented
+ }
+ if (ctx.type == "statement")
+ return ctx.indented + (firstChar == "{" ? 0 : statementIndentUnit);
+ if (ctx.align && (!dontAlignCalls || ctx.type != ")"))
+ return ctx.column + (closing ? 0 : 1);
+ if (ctx.type == ")" && !closing)
+ return ctx.indented + statementIndentUnit;
+
+ return ctx.indented + (closing ? 0 : indentUnit) +
+ (!closing && switchBlock && !/^(?:case|default)\b/.test(textAfter) ? indentUnit : 0);
+ },
+
+ electricInput: indentSwitch ? /^\s*(?:case .*?:|default:|\{\}?|\})$/ : /^\s*[{}]$/,
+ blockCommentStart: "/*",
+ blockCommentEnd: "*/",
+ blockCommentContinue: " * ",
+ lineComment: "//",
+ fold: "brace"
+ };
+});
+
+ function words(str) {
+ var obj = {}, words = str.split(" ");
+ for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+ return obj;
+ }
+ function contains(words, word) {
+ if (typeof words === "function") {
+ return words(word);
+ } else {
+ return words.propertyIsEnumerable(word);
+ }
+ }
+ var cKeywords = "auto if break case register continue return default do sizeof " +
+ "static else struct switch extern typedef union for goto while enum const " +
+ "volatile inline restrict asm fortran";
+
+ // Do not use this. Use the cTypes function below. This is global just to avoid
+ // excessive calls when cTypes is being called multiple times during a parse.
+ var basicCTypes = words("int long char short double float unsigned signed " +
+ "void bool");
+
+ // Do not use this. Use the objCTypes function below. This is global just to avoid
+ // excessive calls when objCTypes is being called multiple times during a parse.
+ var basicObjCTypes = words("SEL instancetype id Class Protocol BOOL");
+
+ // Returns true if identifier is a "C" type.
+ // C type is defined as those that are reserved by the compiler (basicTypes),
+ // and those that end in _t (Reserved by POSIX for types)
+ // http://www.gnu.org/software/libc/manual/html_node/Reserved-Names.html
+ function cTypes(identifier) {
+ return contains(basicCTypes, identifier) || /.+_t$/.test(identifier);
+ }
+
+ // Returns true if identifier is a "Objective C" type.
+ function objCTypes(identifier) {
+ return cTypes(identifier) || contains(basicObjCTypes, identifier);
+ }
+
+ var cBlockKeywords = "case do else for if switch while struct enum union";
+ var cDefKeywords = "struct enum union";
+
+ function cppHook(stream, state) {
+ if (!state.startOfLine) return false
+ for (var ch, next = null; ch = stream.peek();) {
+ if (ch == "\\" && stream.match(/^.$/)) {
+ next = cppHook
+ break
+ } else if (ch == "/" && stream.match(/^\/[\/\*]/, false)) {
+ break
+ }
+ stream.next()
+ }
+ state.tokenize = next
+ return "meta"
+ }
+
+ function pointerHook(_stream, state) {
+ if (state.prevToken == "type") return "type";
+ return false;
+ }
+
+ // For C and C++ (and ObjC): identifiers starting with __
+ // or _ followed by a capital letter are reserved for the compiler.
+ function cIsReservedIdentifier(token) {
+ if (!token || token.length < 2) return false;
+ if (token[0] != '_') return false;
+ return (token[1] == '_') || (token[1] !== token[1].toLowerCase());
+ }
+
+ function cpp14Literal(stream) {
+ stream.eatWhile(/[\w\.']/);
+ return "number";
+ }
+
+ function cpp11StringHook(stream, state) {
+ stream.backUp(1);
+ // Raw strings.
+ if (stream.match(/(R|u8R|uR|UR|LR)/)) {
+ var match = stream.match(/"([^\s\\()]{0,16})\(/);
+ if (!match) {
+ return false;
+ }
+ state.cpp11RawStringDelim = match[1];
+ state.tokenize = tokenRawString;
+ return tokenRawString(stream, state);
+ }
+ // Unicode strings/chars.
+ if (stream.match(/(u8|u|U|L)/)) {
+ if (stream.match(/["']/, /* eat */ false)) {
+ return "string";
+ }
+ return false;
+ }
+ // Ignore this hook.
+ stream.next();
+ return false;
+ }
+
+ function cppLooksLikeConstructor(word) {
+ var lastTwo = /(\w+)::~?(\w+)$/.exec(word);
+ return lastTwo && lastTwo[1] == lastTwo[2];
+ }
+
+ // C#-style strings where "" escapes a quote.
+ function tokenAtString(stream, state) {
+ var next;
+ while ((next = stream.next()) != null) {
+ if (next == '"' && !stream.eat('"')) {
+ state.tokenize = null;
+ break;
+ }
+ }
+ return "string";
+ }
+
+ // C++11 raw string literal is <prefix>"<delim>( anything )<delim>", where
+ // <delim> can be a string up to 16 characters long.
+ function tokenRawString(stream, state) {
+ // Escape characters that have special regex meanings.
+ var delim = state.cpp11RawStringDelim.replace(/[^\w\s]/g, '\\$&');
+ var match = stream.match(new RegExp(".*?\\)" + delim + '"'));
+ if (match)
+ state.tokenize = null;
+ else
+ stream.skipToEnd();
+ return "string";
+ }
+
+ function def(mimes, mode) {
+ if (typeof mimes == "string") mimes = [mimes];
+ var words = [];
+ function add(obj) {
+ if (obj) for (var prop in obj) if (obj.hasOwnProperty(prop))
+ words.push(prop);
+ }
+ add(mode.keywords);
+ add(mode.types);
+ add(mode.builtin);
+ add(mode.atoms);
+ if (words.length) {
+ mode.helperType = mimes[0];
+ CodeMirror.registerHelper("hintWords", mimes[0], words);
+ }
+
+ for (var i = 0; i < mimes.length; ++i)
+ CodeMirror.defineMIME(mimes[i], mode);
+ }
+
+ def(["text/x-csrc", "text/x-c", "text/x-chdr"], {
+ name: "clike",
+ keywords: words(cKeywords),
+ types: cTypes,
+ blockKeywords: words(cBlockKeywords),
+ defKeywords: words(cDefKeywords),
+ typeFirstDefinitions: true,
+ atoms: words("NULL true false"),
+ isReservedIdentifier: cIsReservedIdentifier,
+ hooks: {
+ "#": cppHook,
+ "*": pointerHook,
+ },
+ modeProps: {fold: ["brace", "include"]}
+ });
+
+ def(["text/x-c++src", "text/x-c++hdr"], {
+ name: "clike",
+ // Keywords from https://en.cppreference.com/w/cpp/keyword includes C++20.
+ keywords: words(cKeywords + "alignas alignof and and_eq audit axiom bitand bitor catch " +
+ "class compl concept constexpr const_cast decltype delete dynamic_cast " +
+ "explicit export final friend import module mutable namespace new noexcept " +
+ "not not_eq operator or or_eq override private protected public " +
+ "reinterpret_cast requires static_assert static_cast template this " +
+ "thread_local throw try typeid typename using virtual xor xor_eq"),
+ types: cTypes,
+ blockKeywords: words(cBlockKeywords + " class try catch"),
+ defKeywords: words(cDefKeywords + " class namespace"),
+ typeFirstDefinitions: true,
+ atoms: words("true false NULL nullptr"),
+ dontIndentStatements: /^template$/,
+ isIdentifierChar: /[\w\$_~\xa1-\uffff]/,
+ isReservedIdentifier: cIsReservedIdentifier,
+ hooks: {
+ "#": cppHook,
+ "*": pointerHook,
+ "u": cpp11StringHook,
+ "U": cpp11StringHook,
+ "L": cpp11StringHook,
+ "R": cpp11StringHook,
+ "0": cpp14Literal,
+ "1": cpp14Literal,
+ "2": cpp14Literal,
+ "3": cpp14Literal,
+ "4": cpp14Literal,
+ "5": cpp14Literal,
+ "6": cpp14Literal,
+ "7": cpp14Literal,
+ "8": cpp14Literal,
+ "9": cpp14Literal,
+ token: function(stream, state, style) {
+ if (style == "variable" && stream.peek() == "(" &&
+ (state.prevToken == ";" || state.prevToken == null ||
+ state.prevToken == "}") &&
+ cppLooksLikeConstructor(stream.current()))
+ return "def";
+ }
+ },
+ namespaceSeparator: "::",
+ modeProps: {fold: ["brace", "include"]}
+ });
+
+ def("text/x-java", {
+ name: "clike",
+ keywords: words("abstract assert break case catch class const continue default " +
+ "do else enum extends final finally for goto if implements import " +
+ "instanceof interface native new package private protected public " +
+ "return static strictfp super switch synchronized this throw throws transient " +
+ "try volatile while @interface"),
+ types: words("byte short int long float double boolean char void Boolean Byte Character Double Float " +
+ "Integer Long Number Object Short String StringBuffer StringBuilder Void"),
+ blockKeywords: words("catch class do else finally for if switch try while"),
+ defKeywords: words("class interface enum @interface"),
+ typeFirstDefinitions: true,
+ atoms: words("true false null"),
+ number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+\.?\d*|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i,
+ hooks: {
+ "@": function(stream) {
+ // Don't match the @interface keyword.
+ if (stream.match('interface', false)) return false;
+
+ stream.eatWhile(/[\w\$_]/);
+ return "meta";
+ }
+ },
+ modeProps: {fold: ["brace", "import"]}
+ });
+
+ def("text/x-csharp", {
+ name: "clike",
+ keywords: words("abstract as async await base break case catch checked class const continue" +
+ " default delegate do else enum event explicit extern finally fixed for" +
+ " foreach goto if implicit in interface internal is lock namespace new" +
+ " operator out override params private protected public readonly ref return sealed" +
+ " sizeof stackalloc static struct switch this throw try typeof unchecked" +
+ " unsafe using virtual void volatile while add alias ascending descending dynamic from get" +
+ " global group into join let orderby partial remove select set value var yield"),
+ types: words("Action Boolean Byte Char DateTime DateTimeOffset Decimal Double Func" +
+ " Guid Int16 Int32 Int64 Object SByte Single String Task TimeSpan UInt16 UInt32" +
+ " UInt64 bool byte char decimal double short int long object" +
+ " sbyte float string ushort uint ulong"),
+ blockKeywords: words("catch class do else finally for foreach if struct switch try while"),
+ defKeywords: words("class interface namespace struct var"),
+ typeFirstDefinitions: true,
+ atoms: words("true false null"),
+ hooks: {
+ "@": function(stream, state) {
+ if (stream.eat('"')) {
+ state.tokenize = tokenAtString;
+ return tokenAtString(stream, state);
+ }
+ stream.eatWhile(/[\w\$_]/);
+ return "meta";
+ }
+ }
+ });
+
+ function tokenTripleString(stream, state) {
+ var escaped = false;
+ while (!stream.eol()) {
+ if (!escaped && stream.match('"""')) {
+ state.tokenize = null;
+ break;
+ }
+ escaped = stream.next() == "\\" && !escaped;
+ }
+ return "string";
+ }
+
+ function tokenNestedComment(depth) {
+ return function (stream, state) {
+ var ch
+ while (ch = stream.next()) {
+ if (ch == "*" && stream.eat("/")) {
+ if (depth == 1) {
+ state.tokenize = null
+ break
+ } else {
+ state.tokenize = tokenNestedComment(depth - 1)
+ return state.tokenize(stream, state)
+ }
+ } else if (ch == "/" && stream.eat("*")) {
+ state.tokenize = tokenNestedComment(depth + 1)
+ return state.tokenize(stream, state)
+ }
+ }
+ return "comment"
+ }
+ }
+
+ def("text/x-scala", {
+ name: "clike",
+ keywords: words(
+ /* scala */
+ "abstract case catch class def do else extends final finally for forSome if " +
+ "implicit import lazy match new null object override package private protected return " +
+ "sealed super this throw trait try type val var while with yield _ " +
+
+ /* package scala */
+ "assert assume require print println printf readLine readBoolean readByte readShort " +
+ "readChar readInt readLong readFloat readDouble"
+ ),
+ types: words(
+ "AnyVal App Application Array BufferedIterator BigDecimal BigInt Char Console Either " +
+ "Enumeration Equiv Error Exception Fractional Function IndexedSeq Int Integral Iterable " +
+ "Iterator List Map Numeric Nil NotNull Option Ordered Ordering PartialFunction PartialOrdering " +
+ "Product Proxy Range Responder Seq Serializable Set Specializable Stream StringBuilder " +
+ "StringContext Symbol Throwable Traversable TraversableOnce Tuple Unit Vector " +
+
+ /* package java.lang */
+ "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
+ "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
+ "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
+ "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void"
+ ),
+ multiLineStrings: true,
+ blockKeywords: words("catch class enum do else finally for forSome if match switch try while"),
+ defKeywords: words("class enum def object package trait type val var"),
+ atoms: words("true false null"),
+ indentStatements: false,
+ indentSwitch: false,
+ isOperatorChar: /[+\-*&%=<>!?|\/#:@]/,
+ hooks: {
+ "@": function(stream) {
+ stream.eatWhile(/[\w\$_]/);
+ return "meta";
+ },
+ '"': function(stream, state) {
+ if (!stream.match('""')) return false;
+ state.tokenize = tokenTripleString;
+ return state.tokenize(stream, state);
+ },
+ "'": function(stream) {
+ stream.eatWhile(/[\w\$_\xa1-\uffff]/);
+ return "atom";
+ },
+ "=": function(stream, state) {
+ var cx = state.context
+ if (cx.type == "}" && cx.align && stream.eat(">")) {
+ state.context = new Context(cx.indented, cx.column, cx.type, cx.info, null, cx.prev)
+ return "operator"
+ } else {
+ return false
+ }
+ },
+
+ "/": function(stream, state) {
+ if (!stream.eat("*")) return false
+ state.tokenize = tokenNestedComment(1)
+ return state.tokenize(stream, state)
+ }
+ },
+ modeProps: {closeBrackets: {pairs: '()[]{}""', triples: '"'}}
+ });
+
+ function tokenKotlinString(tripleString){
+ return function (stream, state) {
+ var escaped = false, next, end = false;
+ while (!stream.eol()) {
+ if (!tripleString && !escaped && stream.match('"') ) {end = true; break;}
+ if (tripleString && stream.match('"""')) {end = true; break;}
+ next = stream.next();
+ if(!escaped && next == "$" && stream.match('{'))
+ stream.skipTo("}");
+ escaped = !escaped && next == "\\" && !tripleString;
+ }
+ if (end || !tripleString)
+ state.tokenize = null;
+ return "string";
+ }
+ }
+
+ def("text/x-kotlin", {
+ name: "clike",
+ keywords: words(
+ /*keywords*/
+ "package as typealias class interface this super val operator " +
+ "var fun for is in This throw return annotation " +
+ "break continue object if else while do try when !in !is as? " +
+
+ /*soft keywords*/
+ "file import where by get set abstract enum open inner override private public internal " +
+ "protected catch finally out final vararg reified dynamic companion constructor init " +
+ "sealed field property receiver param sparam lateinit data inline noinline tailrec " +
+ "external annotation crossinline const operator infix suspend actual expect setparam"
+ ),
+ types: words(
+ /* package java.lang */
+ "Boolean Byte Character CharSequence Class ClassLoader Cloneable Comparable " +
+ "Compiler Double Exception Float Integer Long Math Number Object Package Pair Process " +
+ "Runtime Runnable SecurityManager Short StackTraceElement StrictMath String " +
+ "StringBuffer System Thread ThreadGroup ThreadLocal Throwable Triple Void Annotation Any BooleanArray " +
+ "ByteArray Char CharArray DeprecationLevel DoubleArray Enum FloatArray Function Int IntArray Lazy " +
+ "LazyThreadSafetyMode LongArray Nothing ShortArray Unit"
+ ),
+ intendSwitch: false,
+ indentStatements: false,
+ multiLineStrings: true,
+ number: /^(?:0x[a-f\d_]+|0b[01_]+|(?:[\d_]+(\.\d+)?|\.\d+)(?:e[-+]?[\d_]+)?)(u|ll?|l|f)?/i,
+ blockKeywords: words("catch class do else finally for if where try while enum"),
+ defKeywords: words("class val var object interface fun"),
+ atoms: words("true false null this"),
+ hooks: {
+ "@": function(stream) {
+ stream.eatWhile(/[\w\$_]/);
+ return "meta";
+ },
+ '*': function(_stream, state) {
+ return state.prevToken == '.' ? 'variable' : 'operator';
+ },
+ '"': function(stream, state) {
+ state.tokenize = tokenKotlinString(stream.match('""'));
+ return state.tokenize(stream, state);
+ },
+ "/": function(stream, state) {
+ if (!stream.eat("*")) return false;
+ state.tokenize = tokenNestedComment(1);
+ return state.tokenize(stream, state)
+ },
+ indent: function(state, ctx, textAfter, indentUnit) {
+ var firstChar = textAfter && textAfter.charAt(0);
+ if ((state.prevToken == "}" || state.prevToken == ")") && textAfter == "")
+ return state.indented;
+ if ((state.prevToken == "operator" && textAfter != "}" && state.context.type != "}") ||
+ state.prevToken == "variable" && firstChar == "." ||
+ (state.prevToken == "}" || state.prevToken == ")") && firstChar == ".")
+ return indentUnit * 2 + ctx.indented;
+ if (ctx.align && ctx.type == "}")
+ return ctx.indented + (state.context.type == (textAfter || "").charAt(0) ? 0 : indentUnit);
+ }
+ },
+ modeProps: {closeBrackets: {triples: '"'}}
+ });
+
+ def(["x-shader/x-vertex", "x-shader/x-fragment"], {
+ name: "clike",
+ keywords: words("sampler1D sampler2D sampler3D samplerCube " +
+ "sampler1DShadow sampler2DShadow " +
+ "const attribute uniform varying " +
+ "break continue discard return " +
+ "for while do if else struct " +
+ "in out inout"),
+ types: words("float int bool void " +
+ "vec2 vec3 vec4 ivec2 ivec3 ivec4 bvec2 bvec3 bvec4 " +
+ "mat2 mat3 mat4"),
+ blockKeywords: words("for while do if else struct"),
+ builtin: words("radians degrees sin cos tan asin acos atan " +
+ "pow exp log exp2 sqrt inversesqrt " +
+ "abs sign floor ceil fract mod min max clamp mix step smoothstep " +
+ "length distance dot cross normalize ftransform faceforward " +
+ "reflect refract matrixCompMult " +
+ "lessThan lessThanEqual greaterThan greaterThanEqual " +
+ "equal notEqual any all not " +
+ "texture1D texture1DProj texture1DLod texture1DProjLod " +
+ "texture2D texture2DProj texture2DLod texture2DProjLod " +
+ "texture3D texture3DProj texture3DLod texture3DProjLod " +
+ "textureCube textureCubeLod " +
+ "shadow1D shadow2D shadow1DProj shadow2DProj " +
+ "shadow1DLod shadow2DLod shadow1DProjLod shadow2DProjLod " +
+ "dFdx dFdy fwidth " +
+ "noise1 noise2 noise3 noise4"),
+ atoms: words("true false " +
+ "gl_FragColor gl_SecondaryColor gl_Normal gl_Vertex " +
+ "gl_MultiTexCoord0 gl_MultiTexCoord1 gl_MultiTexCoord2 gl_MultiTexCoord3 " +
+ "gl_MultiTexCoord4 gl_MultiTexCoord5 gl_MultiTexCoord6 gl_MultiTexCoord7 " +
+ "gl_FogCoord gl_PointCoord " +
+ "gl_Position gl_PointSize gl_ClipVertex " +
+ "gl_FrontColor gl_BackColor gl_FrontSecondaryColor gl_BackSecondaryColor " +
+ "gl_TexCoord gl_FogFragCoord " +
+ "gl_FragCoord gl_FrontFacing " +
+ "gl_FragData gl_FragDepth " +
+ "gl_ModelViewMatrix gl_ProjectionMatrix gl_ModelViewProjectionMatrix " +
+ "gl_TextureMatrix gl_NormalMatrix gl_ModelViewMatrixInverse " +
+ "gl_ProjectionMatrixInverse gl_ModelViewProjectionMatrixInverse " +
+ "gl_TexureMatrixTranspose gl_ModelViewMatrixInverseTranspose " +
+ "gl_ProjectionMatrixInverseTranspose " +
+ "gl_ModelViewProjectionMatrixInverseTranspose " +
+ "gl_TextureMatrixInverseTranspose " +
+ "gl_NormalScale gl_DepthRange gl_ClipPlane " +
+ "gl_Point gl_FrontMaterial gl_BackMaterial gl_LightSource gl_LightModel " +
+ "gl_FrontLightModelProduct gl_BackLightModelProduct " +
+ "gl_TextureColor gl_EyePlaneS gl_EyePlaneT gl_EyePlaneR gl_EyePlaneQ " +
+ "gl_FogParameters " +
+ "gl_MaxLights gl_MaxClipPlanes gl_MaxTextureUnits gl_MaxTextureCoords " +
+ "gl_MaxVertexAttribs gl_MaxVertexUniformComponents gl_MaxVaryingFloats " +
+ "gl_MaxVertexTextureImageUnits gl_MaxTextureImageUnits " +
+ "gl_MaxFragmentUniformComponents gl_MaxCombineTextureImageUnits " +
+ "gl_MaxDrawBuffers"),
+ indentSwitch: false,
+ hooks: {"#": cppHook},
+ modeProps: {fold: ["brace", "include"]}
+ });
+
+ def("text/x-nesc", {
+ name: "clike",
+ keywords: words(cKeywords + " as atomic async call command component components configuration event generic " +
+ "implementation includes interface module new norace nx_struct nx_union post provides " +
+ "signal task uses abstract extends"),
+ types: cTypes,
+ blockKeywords: words(cBlockKeywords),
+ atoms: words("null true false"),
+ hooks: {"#": cppHook},
+ modeProps: {fold: ["brace", "include"]}
+ });
+
+ def("text/x-objectivec", {
+ name: "clike",
+ keywords: words(cKeywords + " bycopy byref in inout oneway out self super atomic nonatomic retain copy " +
+ "readwrite readonly strong weak assign typeof nullable nonnull null_resettable _cmd " +
+ "@interface @implementation @end @protocol @encode @property @synthesize @dynamic @class " +
+ "@public @package @private @protected @required @optional @try @catch @finally @import " +
+ "@selector @encode @defs @synchronized @autoreleasepool @compatibility_alias @available"),
+ types: objCTypes,
+ builtin: words("FOUNDATION_EXPORT FOUNDATION_EXTERN NS_INLINE NS_FORMAT_FUNCTION NS_RETURNS_RETAINED " +
+ "NS_ERROR_ENUM NS_RETURNS_NOT_RETAINED NS_RETURNS_INNER_POINTER NS_DESIGNATED_INITIALIZER " +
+ "NS_ENUM NS_OPTIONS NS_REQUIRES_NIL_TERMINATION NS_ASSUME_NONNULL_BEGIN " +
+ "NS_ASSUME_NONNULL_END NS_SWIFT_NAME NS_REFINED_FOR_SWIFT"),
+ blockKeywords: words(cBlockKeywords + " @synthesize @try @catch @finally @autoreleasepool @synchronized"),
+ defKeywords: words(cDefKeywords + " @interface @implementation @protocol @class"),
+ dontIndentStatements: /^@.*$/,
+ typeFirstDefinitions: true,
+ atoms: words("YES NO NULL Nil nil true false nullptr"),
+ isReservedIdentifier: cIsReservedIdentifier,
+ hooks: {
+ "#": cppHook,
+ "*": pointerHook,
+ },
+ modeProps: {fold: ["brace", "include"]}
+ });
+
+ def("text/x-squirrel", {
+ name: "clike",
+ keywords: words("base break clone continue const default delete enum extends function in class" +
+ " foreach local resume return this throw typeof yield constructor instanceof static"),
+ types: cTypes,
+ blockKeywords: words("case catch class else for foreach if switch try while"),
+ defKeywords: words("function local class"),
+ typeFirstDefinitions: true,
+ atoms: words("true false null"),
+ hooks: {"#": cppHook},
+ modeProps: {fold: ["brace", "include"]}
+ });
+
+ // Ceylon Strings need to deal with interpolation
+ var stringTokenizer = null;
+ function tokenCeylonString(type) {
+ return function(stream, state) {
+ var escaped = false, next, end = false;
+ while (!stream.eol()) {
+ if (!escaped && stream.match('"') &&
+ (type == "single" || stream.match('""'))) {
+ end = true;
+ break;
+ }
+ if (!escaped && stream.match('``')) {
+ stringTokenizer = tokenCeylonString(type);
+ end = true;
+ break;
+ }
+ next = stream.next();
+ escaped = type == "single" && !escaped && next == "\\";
+ }
+ if (end)
+ state.tokenize = null;
+ return "string";
+ }
+ }
+
+ def("text/x-ceylon", {
+ name: "clike",
+ keywords: words("abstracts alias assembly assert assign break case catch class continue dynamic else" +
+ " exists extends finally for function given if import in interface is let module new" +
+ " nonempty object of out outer package return satisfies super switch then this throw" +
+ " try value void while"),
+ types: function(word) {
+ // In Ceylon all identifiers that start with an uppercase are types
+ var first = word.charAt(0);
+ return (first === first.toUpperCase() && first !== first.toLowerCase());
+ },
+ blockKeywords: words("case catch class dynamic else finally for function if interface module new object switch try while"),
+ defKeywords: words("class dynamic function interface module object package value"),
+ builtin: words("abstract actual aliased annotation by default deprecated doc final formal late license" +
+ " native optional sealed see serializable shared suppressWarnings tagged throws variable"),
+ isPunctuationChar: /[\[\]{}\(\),;\:\.`]/,
+ isOperatorChar: /[+\-*&%=<>!?|^~:\/]/,
+ numberStart: /[\d#$]/,
+ number: /^(?:#[\da-fA-F_]+|\$[01_]+|[\d_]+[kMGTPmunpf]?|[\d_]+\.[\d_]+(?:[eE][-+]?\d+|[kMGTPmunpf]|)|)/i,
+ multiLineStrings: true,
+ typeFirstDefinitions: true,
+ atoms: words("true false null larger smaller equal empty finished"),
+ indentSwitch: false,
+ styleDefs: false,
+ hooks: {
+ "@": function(stream) {
+ stream.eatWhile(/[\w\$_]/);
+ return "meta";
+ },
+ '"': function(stream, state) {
+ state.tokenize = tokenCeylonString(stream.match('""') ? "triple" : "single");
+ return state.tokenize(stream, state);
+ },
+ '`': function(stream, state) {
+ if (!stringTokenizer || !stream.match('`')) return false;
+ state.tokenize = stringTokenizer;
+ stringTokenizer = null;
+ return state.tokenize(stream, state);
+ },
+ "'": function(stream) {
+ stream.eatWhile(/[\w\$_\xa1-\uffff]/);
+ return "atom";
+ },
+ token: function(_stream, state, style) {
+ if ((style == "variable" || style == "type") &&
+ state.prevToken == ".") {
+ return "variable-2";
+ }
+ }
+ },
+ modeProps: {
+ fold: ["brace", "import"],
+ closeBrackets: {triples: '"'}
+ }
+ });
+
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/mode/clojure/clojure.js b/devtools/client/shared/sourceeditor/codemirror/mode/clojure/clojure.js
new file mode 100644
index 0000000000..5f14c55d19
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/mode/clojure/clojure.js
@@ -0,0 +1,292 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports === "object" && typeof module === "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define === "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+"use strict";
+
+CodeMirror.defineMode("clojure", function (options) {
+ var atoms = ["false", "nil", "true"];
+ var specialForms = [".", "catch", "def", "do", "if", "monitor-enter",
+ "monitor-exit", "new", "quote", "recur", "set!", "throw", "try", "var"];
+ var coreSymbols = ["*", "*'", "*1", "*2", "*3", "*agent*",
+ "*allow-unresolved-vars*", "*assert*", "*clojure-version*",
+ "*command-line-args*", "*compile-files*", "*compile-path*",
+ "*compiler-options*", "*data-readers*", "*default-data-reader-fn*", "*e",
+ "*err*", "*file*", "*flush-on-newline*", "*fn-loader*", "*in*",
+ "*math-context*", "*ns*", "*out*", "*print-dup*", "*print-length*",
+ "*print-level*", "*print-meta*", "*print-namespace-maps*",
+ "*print-readably*", "*read-eval*", "*reader-resolver*", "*source-path*",
+ "*suppress-read*", "*unchecked-math*", "*use-context-classloader*",
+ "*verbose-defrecords*", "*warn-on-reflection*", "+", "+'", "-", "-'",
+ "->", "->>", "->ArrayChunk", "->Eduction", "->Vec", "->VecNode",
+ "->VecSeq", "-cache-protocol-fn", "-reset-methods", "..", "/", "<", "<=",
+ "=", "==", ">", ">=", "EMPTY-NODE", "Inst", "StackTraceElement->vec",
+ "Throwable->map", "accessor", "aclone", "add-classpath", "add-watch",
+ "agent", "agent-error", "agent-errors", "aget", "alength", "alias",
+ "all-ns", "alter", "alter-meta!", "alter-var-root", "amap", "ancestors",
+ "and", "any?", "apply", "areduce", "array-map", "as->", "aset",
+ "aset-boolean", "aset-byte", "aset-char", "aset-double", "aset-float",
+ "aset-int", "aset-long", "aset-short", "assert", "assoc", "assoc!",
+ "assoc-in", "associative?", "atom", "await", "await-for", "await1",
+ "bases", "bean", "bigdec", "bigint", "biginteger", "binding", "bit-and",
+ "bit-and-not", "bit-clear", "bit-flip", "bit-not", "bit-or", "bit-set",
+ "bit-shift-left", "bit-shift-right", "bit-test", "bit-xor", "boolean",
+ "boolean-array", "boolean?", "booleans", "bound-fn", "bound-fn*",
+ "bound?", "bounded-count", "butlast", "byte", "byte-array", "bytes",
+ "bytes?", "case", "cast", "cat", "char", "char-array",
+ "char-escape-string", "char-name-string", "char?", "chars", "chunk",
+ "chunk-append", "chunk-buffer", "chunk-cons", "chunk-first", "chunk-next",
+ "chunk-rest", "chunked-seq?", "class", "class?", "clear-agent-errors",
+ "clojure-version", "coll?", "comment", "commute", "comp", "comparator",
+ "compare", "compare-and-set!", "compile", "complement", "completing",
+ "concat", "cond", "cond->", "cond->>", "condp", "conj", "conj!", "cons",
+ "constantly", "construct-proxy", "contains?", "count", "counted?",
+ "create-ns", "create-struct", "cycle", "dec", "dec'", "decimal?",
+ "declare", "dedupe", "default-data-readers", "definline", "definterface",
+ "defmacro", "defmethod", "defmulti", "defn", "defn-", "defonce",
+ "defprotocol", "defrecord", "defstruct", "deftype", "delay", "delay?",
+ "deliver", "denominator", "deref", "derive", "descendants", "destructure",
+ "disj", "disj!", "dissoc", "dissoc!", "distinct", "distinct?", "doall",
+ "dorun", "doseq", "dosync", "dotimes", "doto", "double", "double-array",
+ "double?", "doubles", "drop", "drop-last", "drop-while", "eduction",
+ "empty", "empty?", "ensure", "ensure-reduced", "enumeration-seq",
+ "error-handler", "error-mode", "eval", "even?", "every-pred", "every?",
+ "ex-data", "ex-info", "extend", "extend-protocol", "extend-type",
+ "extenders", "extends?", "false?", "ffirst", "file-seq", "filter",
+ "filterv", "find", "find-keyword", "find-ns", "find-protocol-impl",
+ "find-protocol-method", "find-var", "first", "flatten", "float",
+ "float-array", "float?", "floats", "flush", "fn", "fn?", "fnext", "fnil",
+ "for", "force", "format", "frequencies", "future", "future-call",
+ "future-cancel", "future-cancelled?", "future-done?", "future?",
+ "gen-class", "gen-interface", "gensym", "get", "get-in", "get-method",
+ "get-proxy-class", "get-thread-bindings", "get-validator", "group-by",
+ "halt-when", "hash", "hash-combine", "hash-map", "hash-ordered-coll",
+ "hash-set", "hash-unordered-coll", "ident?", "identical?", "identity",
+ "if-let", "if-not", "if-some", "ifn?", "import", "in-ns", "inc", "inc'",
+ "indexed?", "init-proxy", "inst-ms", "inst-ms*", "inst?", "instance?",
+ "int", "int-array", "int?", "integer?", "interleave", "intern",
+ "interpose", "into", "into-array", "ints", "io!", "isa?", "iterate",
+ "iterator-seq", "juxt", "keep", "keep-indexed", "key", "keys", "keyword",
+ "keyword?", "last", "lazy-cat", "lazy-seq", "let", "letfn", "line-seq",
+ "list", "list*", "list?", "load", "load-file", "load-reader",
+ "load-string", "loaded-libs", "locking", "long", "long-array", "longs",
+ "loop", "macroexpand", "macroexpand-1", "make-array", "make-hierarchy",
+ "map", "map-entry?", "map-indexed", "map?", "mapcat", "mapv", "max",
+ "max-key", "memfn", "memoize", "merge", "merge-with", "meta",
+ "method-sig", "methods", "min", "min-key", "mix-collection-hash", "mod",
+ "munge", "name", "namespace", "namespace-munge", "nat-int?", "neg-int?",
+ "neg?", "newline", "next", "nfirst", "nil?", "nnext", "not", "not-any?",
+ "not-empty", "not-every?", "not=", "ns", "ns-aliases", "ns-imports",
+ "ns-interns", "ns-map", "ns-name", "ns-publics", "ns-refers",
+ "ns-resolve", "ns-unalias", "ns-unmap", "nth", "nthnext", "nthrest",
+ "num", "number?", "numerator", "object-array", "odd?", "or", "parents",
+ "partial", "partition", "partition-all", "partition-by", "pcalls", "peek",
+ "persistent!", "pmap", "pop", "pop!", "pop-thread-bindings", "pos-int?",
+ "pos?", "pr", "pr-str", "prefer-method", "prefers",
+ "primitives-classnames", "print", "print-ctor", "print-dup",
+ "print-method", "print-simple", "print-str", "printf", "println",
+ "println-str", "prn", "prn-str", "promise", "proxy",
+ "proxy-call-with-super", "proxy-mappings", "proxy-name", "proxy-super",
+ "push-thread-bindings", "pvalues", "qualified-ident?",
+ "qualified-keyword?", "qualified-symbol?", "quot", "rand", "rand-int",
+ "rand-nth", "random-sample", "range", "ratio?", "rational?",
+ "rationalize", "re-find", "re-groups", "re-matcher", "re-matches",
+ "re-pattern", "re-seq", "read", "read-line", "read-string",
+ "reader-conditional", "reader-conditional?", "realized?", "record?",
+ "reduce", "reduce-kv", "reduced", "reduced?", "reductions", "ref",
+ "ref-history-count", "ref-max-history", "ref-min-history", "ref-set",
+ "refer", "refer-clojure", "reify", "release-pending-sends", "rem",
+ "remove", "remove-all-methods", "remove-method", "remove-ns",
+ "remove-watch", "repeat", "repeatedly", "replace", "replicate", "require",
+ "reset!", "reset-meta!", "reset-vals!", "resolve", "rest",
+ "restart-agent", "resultset-seq", "reverse", "reversible?", "rseq",
+ "rsubseq", "run!", "satisfies?", "second", "select-keys", "send",
+ "send-off", "send-via", "seq", "seq?", "seqable?", "seque", "sequence",
+ "sequential?", "set", "set-agent-send-executor!",
+ "set-agent-send-off-executor!", "set-error-handler!", "set-error-mode!",
+ "set-validator!", "set?", "short", "short-array", "shorts", "shuffle",
+ "shutdown-agents", "simple-ident?", "simple-keyword?", "simple-symbol?",
+ "slurp", "some", "some->", "some->>", "some-fn", "some?", "sort",
+ "sort-by", "sorted-map", "sorted-map-by", "sorted-set", "sorted-set-by",
+ "sorted?", "special-symbol?", "spit", "split-at", "split-with", "str",
+ "string?", "struct", "struct-map", "subs", "subseq", "subvec", "supers",
+ "swap!", "swap-vals!", "symbol", "symbol?", "sync", "tagged-literal",
+ "tagged-literal?", "take", "take-last", "take-nth", "take-while", "test",
+ "the-ns", "thread-bound?", "time", "to-array", "to-array-2d",
+ "trampoline", "transduce", "transient", "tree-seq", "true?", "type",
+ "unchecked-add", "unchecked-add-int", "unchecked-byte", "unchecked-char",
+ "unchecked-dec", "unchecked-dec-int", "unchecked-divide-int",
+ "unchecked-double", "unchecked-float", "unchecked-inc",
+ "unchecked-inc-int", "unchecked-int", "unchecked-long",
+ "unchecked-multiply", "unchecked-multiply-int", "unchecked-negate",
+ "unchecked-negate-int", "unchecked-remainder-int", "unchecked-short",
+ "unchecked-subtract", "unchecked-subtract-int", "underive", "unquote",
+ "unquote-splicing", "unreduced", "unsigned-bit-shift-right", "update",
+ "update-in", "update-proxy", "uri?", "use", "uuid?", "val", "vals",
+ "var-get", "var-set", "var?", "vary-meta", "vec", "vector", "vector-of",
+ "vector?", "volatile!", "volatile?", "vreset!", "vswap!", "when",
+ "when-first", "when-let", "when-not", "when-some", "while",
+ "with-bindings", "with-bindings*", "with-in-str", "with-loading-context",
+ "with-local-vars", "with-meta", "with-open", "with-out-str",
+ "with-precision", "with-redefs", "with-redefs-fn", "xml-seq", "zero?",
+ "zipmap"];
+ var haveBodyParameter = [
+ "->", "->>", "as->", "binding", "bound-fn", "case", "catch", "comment",
+ "cond", "cond->", "cond->>", "condp", "def", "definterface", "defmethod",
+ "defn", "defmacro", "defprotocol", "defrecord", "defstruct", "deftype",
+ "do", "doseq", "dotimes", "doto", "extend", "extend-protocol",
+ "extend-type", "fn", "for", "future", "if", "if-let", "if-not", "if-some",
+ "let", "letfn", "locking", "loop", "ns", "proxy", "reify", "struct-map",
+ "some->", "some->>", "try", "when", "when-first", "when-let", "when-not",
+ "when-some", "while", "with-bindings", "with-bindings*", "with-in-str",
+ "with-loading-context", "with-local-vars", "with-meta", "with-open",
+ "with-out-str", "with-precision", "with-redefs", "with-redefs-fn"];
+
+ CodeMirror.registerHelper("hintWords", "clojure",
+ [].concat(atoms, specialForms, coreSymbols));
+
+ var atom = createLookupMap(atoms);
+ var specialForm = createLookupMap(specialForms);
+ var coreSymbol = createLookupMap(coreSymbols);
+ var hasBodyParameter = createLookupMap(haveBodyParameter);
+ var delimiter = /^(?:[\\\[\]\s"(),;@^`{}~]|$)/;
+ var numberLiteral = /^(?:[+\-]?\d+(?:(?:N|(?:[eE][+\-]?\d+))|(?:\.?\d*(?:M|(?:[eE][+\-]?\d+))?)|\/\d+|[xX][0-9a-fA-F]+|r[0-9a-zA-Z]+)?(?=[\\\[\]\s"#'(),;@^`{}~]|$))/;
+ var characterLiteral = /^(?:\\(?:backspace|formfeed|newline|return|space|tab|o[0-7]{3}|u[0-9A-Fa-f]{4}|x[0-9A-Fa-f]{4}|.)?(?=[\\\[\]\s"(),;@^`{}~]|$))/;
+
+ // simple-namespace := /^[^\\\/\[\]\d\s"#'(),;@^`{}~][^\\\[\]\s"(),;@^`{}~]*/
+ // simple-symbol := /^(?:\/|[^\\\/\[\]\d\s"#'(),;@^`{}~][^\\\[\]\s"(),;@^`{}~]*)/
+ // qualified-symbol := (<simple-namespace>(<.><simple-namespace>)*</>)?<simple-symbol>
+ var qualifiedSymbol = /^(?:(?:[^\\\/\[\]\d\s"#'(),;@^`{}~][^\\\[\]\s"(),;@^`{}~]*(?:\.[^\\\/\[\]\d\s"#'(),;@^`{}~][^\\\[\]\s"(),;@^`{}~]*)*\/)?(?:\/|[^\\\/\[\]\d\s"#'(),;@^`{}~][^\\\[\]\s"(),;@^`{}~]*)*(?=[\\\[\]\s"(),;@^`{}~]|$))/;
+
+ function base(stream, state) {
+ if (stream.eatSpace() || stream.eat(",")) return ["space", null];
+ if (stream.match(numberLiteral)) return [null, "number"];
+ if (stream.match(characterLiteral)) return [null, "string-2"];
+ if (stream.eat(/^"/)) return (state.tokenize = inString)(stream, state);
+ if (stream.eat(/^[(\[{]/)) return ["open", "bracket"];
+ if (stream.eat(/^[)\]}]/)) return ["close", "bracket"];
+ if (stream.eat(/^;/)) {stream.skipToEnd(); return ["space", "comment"];}
+ if (stream.eat(/^[#'@^`~]/)) return [null, "meta"];
+
+ var matches = stream.match(qualifiedSymbol);
+ var symbol = matches && matches[0];
+
+ if (!symbol) {
+ // advance stream by at least one character so we don't get stuck.
+ stream.next();
+ stream.eatWhile(function (c) {return !is(c, delimiter);});
+ return [null, "error"];
+ }
+
+ if (symbol === "comment" && state.lastToken === "(")
+ return (state.tokenize = inComment)(stream, state);
+ if (is(symbol, atom) || symbol.charAt(0) === ":") return ["symbol", "atom"];
+ if (is(symbol, specialForm) || is(symbol, coreSymbol)) return ["symbol", "keyword"];
+ if (state.lastToken === "(") return ["symbol", "builtin"]; // other operator
+
+ return ["symbol", "variable"];
+ }
+
+ function inString(stream, state) {
+ var escaped = false, next;
+
+ while (next = stream.next()) {
+ if (next === "\"" && !escaped) {state.tokenize = base; break;}
+ escaped = !escaped && next === "\\";
+ }
+
+ return [null, "string"];
+ }
+
+ function inComment(stream, state) {
+ var parenthesisCount = 1;
+ var next;
+
+ while (next = stream.next()) {
+ if (next === ")") parenthesisCount--;
+ if (next === "(") parenthesisCount++;
+ if (parenthesisCount === 0) {
+ stream.backUp(1);
+ state.tokenize = base;
+ break;
+ }
+ }
+
+ return ["space", "comment"];
+ }
+
+ function createLookupMap(words) {
+ var obj = {};
+
+ for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
+
+ return obj;
+ }
+
+ function is(value, test) {
+ if (test instanceof RegExp) return test.test(value);
+ if (test instanceof Object) return test.propertyIsEnumerable(value);
+ }
+
+ return {
+ startState: function () {
+ return {
+ ctx: {prev: null, start: 0, indentTo: 0},
+ lastToken: null,
+ tokenize: base
+ };
+ },
+
+ token: function (stream, state) {
+ if (stream.sol() && (typeof state.ctx.indentTo !== "number"))
+ state.ctx.indentTo = state.ctx.start + 1;
+
+ var typeStylePair = state.tokenize(stream, state);
+ var type = typeStylePair[0];
+ var style = typeStylePair[1];
+ var current = stream.current();
+
+ if (type !== "space") {
+ if (state.lastToken === "(" && state.ctx.indentTo === null) {
+ if (type === "symbol" && is(current, hasBodyParameter))
+ state.ctx.indentTo = state.ctx.start + options.indentUnit;
+ else state.ctx.indentTo = "next";
+ } else if (state.ctx.indentTo === "next") {
+ state.ctx.indentTo = stream.column();
+ }
+
+ state.lastToken = current;
+ }
+
+ if (type === "open")
+ state.ctx = {prev: state.ctx, start: stream.column(), indentTo: null};
+ else if (type === "close") state.ctx = state.ctx.prev || state.ctx;
+
+ return style;
+ },
+
+ indent: function (state) {
+ var i = state.ctx.indentTo;
+
+ return (typeof i === "number") ?
+ i :
+ state.ctx.start + 1;
+ },
+
+ closeBrackets: {pairs: "()[]{}\"\""},
+ lineComment: ";;"
+ };
+});
+
+CodeMirror.defineMIME("text/x-clojure", "clojure");
+CodeMirror.defineMIME("text/x-clojurescript", "clojure");
+CodeMirror.defineMIME("application/edn", "clojure");
+
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/mode/coffeescript/coffeescript.js b/devtools/client/shared/sourceeditor/codemirror/mode/coffeescript/coffeescript.js
new file mode 100644
index 0000000000..c513a3bb81
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/mode/coffeescript/coffeescript.js
@@ -0,0 +1,359 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+/**
+ * Link to the project's GitHub page:
+ * https://github.com/pickhardt/coffeescript-codemirror-mode
+ */
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+"use strict";
+
+CodeMirror.defineMode("coffeescript", function(conf, parserConf) {
+ var ERRORCLASS = "error";
+
+ function wordRegexp(words) {
+ return new RegExp("^((" + words.join(")|(") + "))\\b");
+ }
+
+ var operators = /^(?:->|=>|\+[+=]?|-[\-=]?|\*[\*=]?|\/[\/=]?|[=!]=|<[><]?=?|>>?=?|%=?|&=?|\|=?|\^=?|\~|!|\?|(or|and|\|\||&&|\?)=)/;
+ var delimiters = /^(?:[()\[\]{},:`=;]|\.\.?\.?)/;
+ var identifiers = /^[_A-Za-z$][_A-Za-z$0-9]*/;
+ var atProp = /^@[_A-Za-z$][_A-Za-z$0-9]*/;
+
+ var wordOperators = wordRegexp(["and", "or", "not",
+ "is", "isnt", "in",
+ "instanceof", "typeof"]);
+ var indentKeywords = ["for", "while", "loop", "if", "unless", "else",
+ "switch", "try", "catch", "finally", "class"];
+ var commonKeywords = ["break", "by", "continue", "debugger", "delete",
+ "do", "in", "of", "new", "return", "then",
+ "this", "@", "throw", "when", "until", "extends"];
+
+ var keywords = wordRegexp(indentKeywords.concat(commonKeywords));
+
+ indentKeywords = wordRegexp(indentKeywords);
+
+
+ var stringPrefixes = /^('{3}|\"{3}|['\"])/;
+ var regexPrefixes = /^(\/{3}|\/)/;
+ var commonConstants = ["Infinity", "NaN", "undefined", "null", "true", "false", "on", "off", "yes", "no"];
+ var constants = wordRegexp(commonConstants);
+
+ // Tokenizers
+ function tokenBase(stream, state) {
+ // Handle scope changes
+ if (stream.sol()) {
+ if (state.scope.align === null) state.scope.align = false;
+ var scopeOffset = state.scope.offset;
+ if (stream.eatSpace()) {
+ var lineOffset = stream.indentation();
+ if (lineOffset > scopeOffset && state.scope.type == "coffee") {
+ return "indent";
+ } else if (lineOffset < scopeOffset) {
+ return "dedent";
+ }
+ return null;
+ } else {
+ if (scopeOffset > 0) {
+ dedent(stream, state);
+ }
+ }
+ }
+ if (stream.eatSpace()) {
+ return null;
+ }
+
+ var ch = stream.peek();
+
+ // Handle docco title comment (single line)
+ if (stream.match("####")) {
+ stream.skipToEnd();
+ return "comment";
+ }
+
+ // Handle multi line comments
+ if (stream.match("###")) {
+ state.tokenize = longComment;
+ return state.tokenize(stream, state);
+ }
+
+ // Single line comment
+ 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) {
+ // prevent from getting extra . on 1..
+ if (stream.peek() == "."){
+ stream.backUp(1);
+ }
+ return "number";
+ }
+ // Integers
+ var intLiteral = false;
+ // Hex
+ if (stream.match(/^-?0x[0-9a-f]+/i)) {
+ intLiteral = true;
+ }
+ // Decimal
+ if (stream.match(/^-?[1-9]\d*(e[\+\-]?\d+)?/)) {
+ intLiteral = true;
+ }
+ // Zero by itself with no other piece of number.
+ if (stream.match(/^-?0(?![\dx])/i)) {
+ intLiteral = true;
+ }
+ if (intLiteral) {
+ return "number";
+ }
+ }
+
+ // Handle strings
+ if (stream.match(stringPrefixes)) {
+ state.tokenize = tokenFactory(stream.current(), false, "string");
+ return state.tokenize(stream, state);
+ }
+ // Handle regex literals
+ if (stream.match(regexPrefixes)) {
+ if (stream.current() != "/" || stream.match(/^.*\//, false)) { // prevent highlight of division
+ state.tokenize = tokenFactory(stream.current(), true, "string-2");
+ return state.tokenize(stream, state);
+ } else {
+ stream.backUp(1);
+ }
+ }
+
+
+
+ // Handle operators and delimiters
+ if (stream.match(operators) || stream.match(wordOperators)) {
+ return "operator";
+ }
+ if (stream.match(delimiters)) {
+ return "punctuation";
+ }
+
+ if (stream.match(constants)) {
+ return "atom";
+ }
+
+ if (stream.match(atProp) || state.prop && stream.match(identifiers)) {
+ return "property";
+ }
+
+ if (stream.match(keywords)) {
+ return "keyword";
+ }
+
+ if (stream.match(identifiers)) {
+ return "variable";
+ }
+
+ // Handle non-detected items
+ stream.next();
+ return ERRORCLASS;
+ }
+
+ function tokenFactory(delimiter, singleline, outclass) {
+ return function(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) {
+ outclass = ERRORCLASS;
+ } else {
+ state.tokenize = tokenBase;
+ }
+ }
+ return outclass;
+ };
+ }
+
+ function longComment(stream, state) {
+ while (!stream.eol()) {
+ stream.eatWhile(/[^#]/);
+ if (stream.match("###")) {
+ state.tokenize = tokenBase;
+ break;
+ }
+ stream.eatWhile("#");
+ }
+ return "comment";
+ }
+
+ function indent(stream, state, type) {
+ type = type || "coffee";
+ var offset = 0, align = false, alignOffset = null;
+ for (var scope = state.scope; scope; scope = scope.prev) {
+ if (scope.type === "coffee" || scope.type == "}") {
+ offset = scope.offset + conf.indentUnit;
+ break;
+ }
+ }
+ if (type !== "coffee") {
+ align = null;
+ alignOffset = stream.column() + stream.current().length;
+ } else if (state.scope.align) {
+ state.scope.align = false;
+ }
+ state.scope = {
+ offset: offset,
+ type: type,
+ prev: state.scope,
+ align: align,
+ alignOffset: alignOffset
+ };
+ }
+
+ function dedent(stream, state) {
+ if (!state.scope.prev) return;
+ if (state.scope.type === "coffee") {
+ var _indent = stream.indentation();
+ var matched = false;
+ for (var scope = state.scope; scope; scope = scope.prev) {
+ if (_indent === scope.offset) {
+ matched = true;
+ break;
+ }
+ }
+ if (!matched) {
+ return true;
+ }
+ while (state.scope.prev && state.scope.offset !== _indent) {
+ state.scope = state.scope.prev;
+ }
+ return false;
+ } else {
+ state.scope = state.scope.prev;
+ return false;
+ }
+ }
+
+ function tokenLexer(stream, state) {
+ var style = state.tokenize(stream, state);
+ var current = stream.current();
+
+ // Handle scope changes.
+ if (current === "return") {
+ state.dedent = true;
+ }
+ if (((current === "->" || current === "=>") && stream.eol())
+ || style === "indent") {
+ indent(stream, state);
+ }
+ var delimiter_index = "[({".indexOf(current);
+ if (delimiter_index !== -1) {
+ indent(stream, state, "])}".slice(delimiter_index, delimiter_index+1));
+ }
+ if (indentKeywords.exec(current)){
+ indent(stream, state);
+ }
+ if (current == "then"){
+ dedent(stream, state);
+ }
+
+
+ if (style === "dedent") {
+ if (dedent(stream, state)) {
+ return ERRORCLASS;
+ }
+ }
+ delimiter_index = "])}".indexOf(current);
+ if (delimiter_index !== -1) {
+ while (state.scope.type == "coffee" && state.scope.prev)
+ state.scope = state.scope.prev;
+ if (state.scope.type == current)
+ state.scope = state.scope.prev;
+ }
+ if (state.dedent && stream.eol()) {
+ if (state.scope.type == "coffee" && state.scope.prev)
+ state.scope = state.scope.prev;
+ state.dedent = false;
+ }
+
+ return style;
+ }
+
+ var external = {
+ startState: function(basecolumn) {
+ return {
+ tokenize: tokenBase,
+ scope: {offset:basecolumn || 0, type:"coffee", prev: null, align: false},
+ prop: false,
+ dedent: 0
+ };
+ },
+
+ token: function(stream, state) {
+ var fillAlign = state.scope.align === null && state.scope;
+ if (fillAlign && stream.sol()) fillAlign.align = false;
+
+ var style = tokenLexer(stream, state);
+ if (style && style != "comment") {
+ if (fillAlign) fillAlign.align = true;
+ state.prop = style == "punctuation" && stream.current() == "."
+ }
+
+ return style;
+ },
+
+ indent: function(state, text) {
+ if (state.tokenize != tokenBase) return 0;
+ var scope = state.scope;
+ var closer = text && "])}".indexOf(text.charAt(0)) > -1;
+ if (closer) while (scope.type == "coffee" && scope.prev) scope = scope.prev;
+ var closes = closer && scope.type === text.charAt(0);
+ if (scope.align)
+ return scope.alignOffset - (closes ? 1 : 0);
+ else
+ return (closes ? scope.prev : scope).offset;
+ },
+
+ lineComment: "#",
+ fold: "indent"
+ };
+ return external;
+});
+
+// IANA registered media type
+// https://www.iana.org/assignments/media-types/
+CodeMirror.defineMIME("application/vnd.coffeescript", "coffeescript");
+
+CodeMirror.defineMIME("text/x-coffeescript", "coffeescript");
+CodeMirror.defineMIME("text/coffeescript", "coffeescript");
+
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/mode/css/css.js b/devtools/client/shared/sourceeditor/codemirror/mode/css/css.js
new file mode 100644
index 0000000000..ad4911bcda
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/mode/css/css.js
@@ -0,0 +1,831 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+"use strict";
+
+CodeMirror.defineMode("css", function(config, parserConfig) {
+ var inline = parserConfig.inline
+ if (!parserConfig.propertyKeywords) parserConfig = CodeMirror.resolveMode("text/css");
+
+ var indentUnit = config.indentUnit,
+ tokenHooks = parserConfig.tokenHooks,
+ documentTypes = parserConfig.documentTypes || {},
+ mediaTypes = parserConfig.mediaTypes || {},
+ mediaFeatures = parserConfig.mediaFeatures || {},
+ mediaValueKeywords = parserConfig.mediaValueKeywords || {},
+ propertyKeywords = parserConfig.propertyKeywords || {},
+ nonStandardPropertyKeywords = parserConfig.nonStandardPropertyKeywords || {},
+ fontProperties = parserConfig.fontProperties || {},
+ counterDescriptors = parserConfig.counterDescriptors || {},
+ colorKeywords = parserConfig.colorKeywords || {},
+ valueKeywords = parserConfig.valueKeywords || {},
+ allowNested = parserConfig.allowNested,
+ lineComment = parserConfig.lineComment,
+ supportsAtComponent = parserConfig.supportsAtComponent === true;
+
+ var type, override;
+ function ret(style, tp) { type = tp; return style; }
+
+ // Tokenizers
+
+ function tokenBase(stream, state) {
+ var ch = stream.next();
+ if (tokenHooks[ch]) {
+ var result = tokenHooks[ch](stream, state);
+ if (result !== false) return result;
+ }
+ if (ch == "@") {
+ stream.eatWhile(/[\w\\\-]/);
+ return ret("def", stream.current());
+ } else if (ch == "=" || (ch == "~" || ch == "|") && stream.eat("=")) {
+ return ret(null, "compare");
+ } else if (ch == "\"" || ch == "'") {
+ state.tokenize = tokenString(ch);
+ return state.tokenize(stream, state);
+ } else if (ch == "#") {
+ stream.eatWhile(/[\w\\\-]/);
+ return ret("atom", "hash");
+ } else if (ch == "!") {
+ stream.match(/^\s*\w*/);
+ return ret("keyword", "important");
+ } else if (/\d/.test(ch) || ch == "." && stream.eat(/\d/)) {
+ stream.eatWhile(/[\w.%]/);
+ return ret("number", "unit");
+ } else if (ch === "-") {
+ if (/[\d.]/.test(stream.peek())) {
+ stream.eatWhile(/[\w.%]/);
+ return ret("number", "unit");
+ } else if (stream.match(/^-[\w\\\-]*/)) {
+ stream.eatWhile(/[\w\\\-]/);
+ if (stream.match(/^\s*:/, false))
+ return ret("variable-2", "variable-definition");
+ return ret("variable-2", "variable");
+ } else if (stream.match(/^\w+-/)) {
+ return ret("meta", "meta");
+ }
+ } else if (/[,+>*\/]/.test(ch)) {
+ return ret(null, "select-op");
+ } else if (ch == "." && stream.match(/^-?[_a-z][_a-z0-9-]*/i)) {
+ return ret("qualifier", "qualifier");
+ } else if (/[:;{}\[\]\(\)]/.test(ch)) {
+ return ret(null, ch);
+ } else if (stream.match(/[\w-.]+(?=\()/)) {
+ if (/^(url(-prefix)?|domain|regexp)$/.test(stream.current().toLowerCase())) {
+ state.tokenize = tokenParenthesized;
+ }
+ return ret("variable callee", "variable");
+ } else if (/[\w\\\-]/.test(ch)) {
+ stream.eatWhile(/[\w\\\-]/);
+ return ret("property", "word");
+ } else {
+ return ret(null, null);
+ }
+ }
+
+ function tokenString(quote) {
+ return function(stream, state) {
+ var escaped = false, ch;
+ while ((ch = stream.next()) != null) {
+ if (ch == quote && !escaped) {
+ if (quote == ")") stream.backUp(1);
+ break;
+ }
+ escaped = !escaped && ch == "\\";
+ }
+ if (ch == quote || !escaped && quote != ")") state.tokenize = null;
+ return ret("string", "string");
+ };
+ }
+
+ function tokenParenthesized(stream, state) {
+ stream.next(); // Must be '('
+ if (!stream.match(/\s*[\"\')]/, false))
+ state.tokenize = tokenString(")");
+ else
+ state.tokenize = null;
+ return ret(null, "(");
+ }
+
+ // Context management
+
+ function Context(type, indent, prev) {
+ this.type = type;
+ this.indent = indent;
+ this.prev = prev;
+ }
+
+ function pushContext(state, stream, type, indent) {
+ state.context = new Context(type, stream.indentation() + (indent === false ? 0 : indentUnit), state.context);
+ return type;
+ }
+
+ function popContext(state) {
+ if (state.context.prev)
+ state.context = state.context.prev;
+ return state.context.type;
+ }
+
+ function pass(type, stream, state) {
+ return states[state.context.type](type, stream, state);
+ }
+ function popAndPass(type, stream, state, n) {
+ for (var i = n || 1; i > 0; i--)
+ state.context = state.context.prev;
+ return pass(type, stream, state);
+ }
+
+ // Parser
+
+ function wordAsValue(stream) {
+ var word = stream.current().toLowerCase();
+ if (valueKeywords.hasOwnProperty(word))
+ override = "atom";
+ else if (colorKeywords.hasOwnProperty(word))
+ override = "keyword";
+ else
+ override = "variable";
+ }
+
+ var states = {};
+
+ states.top = function(type, stream, state) {
+ if (type == "{") {
+ return pushContext(state, stream, "block");
+ } else if (type == "}" && state.context.prev) {
+ return popContext(state);
+ } else if (supportsAtComponent && /@component/i.test(type)) {
+ return pushContext(state, stream, "atComponentBlock");
+ } else if (/^@(-moz-)?document$/i.test(type)) {
+ return pushContext(state, stream, "documentTypes");
+ } else if (/^@(media|supports|(-moz-)?document|import)$/i.test(type)) {
+ return pushContext(state, stream, "atBlock");
+ } else if (/^@(font-face|counter-style)/i.test(type)) {
+ state.stateArg = type;
+ return "restricted_atBlock_before";
+ } else if (/^@(-(moz|ms|o|webkit)-)?keyframes$/i.test(type)) {
+ return "keyframes";
+ } else if (type && type.charAt(0) == "@") {
+ return pushContext(state, stream, "at");
+ } else if (type == "hash") {
+ override = "builtin";
+ } else if (type == "word") {
+ override = "tag";
+ } else if (type == "variable-definition") {
+ return "maybeprop";
+ } else if (type == "interpolation") {
+ return pushContext(state, stream, "interpolation");
+ } else if (type == ":") {
+ return "pseudo";
+ } else if (allowNested && type == "(") {
+ return pushContext(state, stream, "parens");
+ }
+ return state.context.type;
+ };
+
+ states.block = function(type, stream, state) {
+ if (type == "word") {
+ var word = stream.current().toLowerCase();
+ if (propertyKeywords.hasOwnProperty(word)) {
+ override = "property";
+ return "maybeprop";
+ } else if (nonStandardPropertyKeywords.hasOwnProperty(word)) {
+ override = "string-2";
+ return "maybeprop";
+ } else if (allowNested) {
+ override = stream.match(/^\s*:(?:\s|$)/, false) ? "property" : "tag";
+ return "block";
+ } else {
+ override += " error";
+ return "maybeprop";
+ }
+ } else if (type == "meta") {
+ return "block";
+ } else if (!allowNested && (type == "hash" || type == "qualifier")) {
+ override = "error";
+ return "block";
+ } else {
+ return states.top(type, stream, state);
+ }
+ };
+
+ states.maybeprop = function(type, stream, state) {
+ if (type == ":") return pushContext(state, stream, "prop");
+ return pass(type, stream, state);
+ };
+
+ states.prop = function(type, stream, state) {
+ if (type == ";") return popContext(state);
+ if (type == "{" && allowNested) return pushContext(state, stream, "propBlock");
+ if (type == "}" || type == "{") return popAndPass(type, stream, state);
+ if (type == "(") return pushContext(state, stream, "parens");
+
+ if (type == "hash" && !/^#([0-9a-fA-f]{3,4}|[0-9a-fA-f]{6}|[0-9a-fA-f]{8})$/.test(stream.current())) {
+ override += " error";
+ } else if (type == "word") {
+ wordAsValue(stream);
+ } else if (type == "interpolation") {
+ return pushContext(state, stream, "interpolation");
+ }
+ return "prop";
+ };
+
+ states.propBlock = function(type, _stream, state) {
+ if (type == "}") return popContext(state);
+ if (type == "word") { override = "property"; return "maybeprop"; }
+ return state.context.type;
+ };
+
+ states.parens = function(type, stream, state) {
+ if (type == "{" || type == "}") return popAndPass(type, stream, state);
+ if (type == ")") return popContext(state);
+ if (type == "(") return pushContext(state, stream, "parens");
+ if (type == "interpolation") return pushContext(state, stream, "interpolation");
+ if (type == "word") wordAsValue(stream);
+ return "parens";
+ };
+
+ states.pseudo = function(type, stream, state) {
+ if (type == "meta") return "pseudo";
+
+ if (type == "word") {
+ override = "variable-3";
+ return state.context.type;
+ }
+ return pass(type, stream, state);
+ };
+
+ states.documentTypes = function(type, stream, state) {
+ if (type == "word" && documentTypes.hasOwnProperty(stream.current())) {
+ override = "tag";
+ return state.context.type;
+ } else {
+ return states.atBlock(type, stream, state);
+ }
+ };
+
+ states.atBlock = function(type, stream, state) {
+ if (type == "(") return pushContext(state, stream, "atBlock_parens");
+ if (type == "}" || type == ";") return popAndPass(type, stream, state);
+ if (type == "{") return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top");
+
+ if (type == "interpolation") return pushContext(state, stream, "interpolation");
+
+ if (type == "word") {
+ var word = stream.current().toLowerCase();
+ if (word == "only" || word == "not" || word == "and" || word == "or")
+ override = "keyword";
+ else if (mediaTypes.hasOwnProperty(word))
+ override = "attribute";
+ else if (mediaFeatures.hasOwnProperty(word))
+ override = "property";
+ else if (mediaValueKeywords.hasOwnProperty(word))
+ override = "keyword";
+ else if (propertyKeywords.hasOwnProperty(word))
+ override = "property";
+ else if (nonStandardPropertyKeywords.hasOwnProperty(word))
+ override = "string-2";
+ else if (valueKeywords.hasOwnProperty(word))
+ override = "atom";
+ else if (colorKeywords.hasOwnProperty(word))
+ override = "keyword";
+ else
+ override = "error";
+ }
+ return state.context.type;
+ };
+
+ states.atComponentBlock = function(type, stream, state) {
+ if (type == "}")
+ return popAndPass(type, stream, state);
+ if (type == "{")
+ return popContext(state) && pushContext(state, stream, allowNested ? "block" : "top", false);
+ if (type == "word")
+ override = "error";
+ return state.context.type;
+ };
+
+ states.atBlock_parens = function(type, stream, state) {
+ if (type == ")") return popContext(state);
+ if (type == "{" || type == "}") return popAndPass(type, stream, state, 2);
+ return states.atBlock(type, stream, state);
+ };
+
+ states.restricted_atBlock_before = function(type, stream, state) {
+ if (type == "{")
+ return pushContext(state, stream, "restricted_atBlock");
+ if (type == "word" && state.stateArg == "@counter-style") {
+ override = "variable";
+ return "restricted_atBlock_before";
+ }
+ return pass(type, stream, state);
+ };
+
+ states.restricted_atBlock = function(type, stream, state) {
+ if (type == "}") {
+ state.stateArg = null;
+ return popContext(state);
+ }
+ if (type == "word") {
+ if ((state.stateArg == "@font-face" && !fontProperties.hasOwnProperty(stream.current().toLowerCase())) ||
+ (state.stateArg == "@counter-style" && !counterDescriptors.hasOwnProperty(stream.current().toLowerCase())))
+ override = "error";
+ else
+ override = "property";
+ return "maybeprop";
+ }
+ return "restricted_atBlock";
+ };
+
+ states.keyframes = function(type, stream, state) {
+ if (type == "word") { override = "variable"; return "keyframes"; }
+ if (type == "{") return pushContext(state, stream, "top");
+ return pass(type, stream, state);
+ };
+
+ states.at = function(type, stream, state) {
+ if (type == ";") return popContext(state);
+ if (type == "{" || type == "}") return popAndPass(type, stream, state);
+ if (type == "word") override = "tag";
+ else if (type == "hash") override = "builtin";
+ return "at";
+ };
+
+ states.interpolation = function(type, stream, state) {
+ if (type == "}") return popContext(state);
+ if (type == "{" || type == ";") return popAndPass(type, stream, state);
+ if (type == "word") override = "variable";
+ else if (type != "variable" && type != "(" && type != ")") override = "error";
+ return "interpolation";
+ };
+
+ return {
+ startState: function(base) {
+ return {tokenize: null,
+ state: inline ? "block" : "top",
+ stateArg: null,
+ context: new Context(inline ? "block" : "top", base || 0, null)};
+ },
+
+ token: function(stream, state) {
+ if (!state.tokenize && stream.eatSpace()) return null;
+ var style = (state.tokenize || tokenBase)(stream, state);
+ if (style && typeof style == "object") {
+ type = style[1];
+ style = style[0];
+ }
+ override = style;
+ if (type != "comment")
+ state.state = states[state.state](type, stream, state);
+ return override;
+ },
+
+ indent: function(state, textAfter) {
+ var cx = state.context, ch = textAfter && textAfter.charAt(0);
+ var indent = cx.indent;
+ if (cx.type == "prop" && (ch == "}" || ch == ")")) cx = cx.prev;
+ if (cx.prev) {
+ if (ch == "}" && (cx.type == "block" || cx.type == "top" ||
+ cx.type == "interpolation" || cx.type == "restricted_atBlock")) {
+ // Resume indentation from parent context.
+ cx = cx.prev;
+ indent = cx.indent;
+ } else if (ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") ||
+ ch == "{" && (cx.type == "at" || cx.type == "atBlock")) {
+ // Dedent relative to current context.
+ indent = Math.max(0, cx.indent - indentUnit);
+ }
+ }
+ return indent;
+ },
+
+ electricChars: "}",
+ blockCommentStart: "/*",
+ blockCommentEnd: "*/",
+ blockCommentContinue: " * ",
+ lineComment: lineComment,
+ fold: "brace"
+ };
+});
+
+ function keySet(array) {
+ var keys = {};
+ for (var i = 0; i < array.length; ++i) {
+ keys[array[i].toLowerCase()] = true;
+ }
+ return keys;
+ }
+
+ var documentTypes_ = [
+ "domain", "regexp", "url", "url-prefix"
+ ], documentTypes = keySet(documentTypes_);
+
+ var mediaTypes_ = [
+ "all", "aural", "braille", "handheld", "print", "projection", "screen",
+ "tty", "tv", "embossed"
+ ], mediaTypes = keySet(mediaTypes_);
+
+ var mediaFeatures_ = [
+ "width", "min-width", "max-width", "height", "min-height", "max-height",
+ "device-width", "min-device-width", "max-device-width", "device-height",
+ "min-device-height", "max-device-height", "aspect-ratio",
+ "min-aspect-ratio", "max-aspect-ratio", "device-aspect-ratio",
+ "min-device-aspect-ratio", "max-device-aspect-ratio", "color", "min-color",
+ "max-color", "color-index", "min-color-index", "max-color-index",
+ "monochrome", "min-monochrome", "max-monochrome", "resolution",
+ "min-resolution", "max-resolution", "scan", "grid", "orientation",
+ "device-pixel-ratio", "min-device-pixel-ratio", "max-device-pixel-ratio",
+ "pointer", "any-pointer", "hover", "any-hover"
+ ], mediaFeatures = keySet(mediaFeatures_);
+
+ var mediaValueKeywords_ = [
+ "landscape", "portrait", "none", "coarse", "fine", "on-demand", "hover",
+ "interlace", "progressive"
+ ], mediaValueKeywords = keySet(mediaValueKeywords_);
+
+ var propertyKeywords_ = [
+ "align-content", "align-items", "align-self", "alignment-adjust",
+ "alignment-baseline", "anchor-point", "animation", "animation-delay",
+ "animation-direction", "animation-duration", "animation-fill-mode",
+ "animation-iteration-count", "animation-name", "animation-play-state",
+ "animation-timing-function", "appearance", "azimuth", "backface-visibility",
+ "background", "background-attachment", "background-blend-mode", "background-clip",
+ "background-color", "background-image", "background-origin", "background-position",
+ "background-repeat", "background-size", "baseline-shift", "binding",
+ "bleed", "bookmark-label", "bookmark-level", "bookmark-state",
+ "bookmark-target", "border", "border-bottom", "border-bottom-color",
+ "border-bottom-left-radius", "border-bottom-right-radius",
+ "border-bottom-style", "border-bottom-width", "border-collapse",
+ "border-color", "border-image", "border-image-outset",
+ "border-image-repeat", "border-image-slice", "border-image-source",
+ "border-image-width", "border-left", "border-left-color",
+ "border-left-style", "border-left-width", "border-radius", "border-right",
+ "border-right-color", "border-right-style", "border-right-width",
+ "border-spacing", "border-style", "border-top", "border-top-color",
+ "border-top-left-radius", "border-top-right-radius", "border-top-style",
+ "border-top-width", "border-width", "bottom", "box-decoration-break",
+ "box-shadow", "box-sizing", "break-after", "break-before", "break-inside",
+ "caption-side", "caret-color", "clear", "clip", "color", "color-profile", "column-count",
+ "column-fill", "column-gap", "column-rule", "column-rule-color",
+ "column-rule-style", "column-rule-width", "column-span", "column-width",
+ "columns", "content", "counter-increment", "counter-reset", "crop", "cue",
+ "cue-after", "cue-before", "cursor", "direction", "display",
+ "dominant-baseline", "drop-initial-after-adjust",
+ "drop-initial-after-align", "drop-initial-before-adjust",
+ "drop-initial-before-align", "drop-initial-size", "drop-initial-value",
+ "elevation", "empty-cells", "fit", "fit-position", "flex", "flex-basis",
+ "flex-direction", "flex-flow", "flex-grow", "flex-shrink", "flex-wrap",
+ "float", "float-offset", "flow-from", "flow-into", "font", "font-feature-settings",
+ "font-family", "font-kerning", "font-language-override", "font-size", "font-size-adjust",
+ "font-stretch", "font-style", "font-synthesis", "font-variant",
+ "font-variant-alternates", "font-variant-caps", "font-variant-east-asian",
+ "font-variant-ligatures", "font-variant-numeric", "font-variant-position",
+ "font-weight", "grid", "grid-area", "grid-auto-columns", "grid-auto-flow",
+ "grid-auto-rows", "grid-column", "grid-column-end", "grid-column-gap",
+ "grid-column-start", "grid-gap", "grid-row", "grid-row-end", "grid-row-gap",
+ "grid-row-start", "grid-template", "grid-template-areas", "grid-template-columns",
+ "grid-template-rows", "hanging-punctuation", "height", "hyphens",
+ "icon", "image-orientation", "image-rendering", "image-resolution",
+ "inline-box-align", "justify-content", "justify-items", "justify-self", "left", "letter-spacing",
+ "line-break", "line-height", "line-stacking", "line-stacking-ruby",
+ "line-stacking-shift", "line-stacking-strategy", "list-style",
+ "list-style-image", "list-style-position", "list-style-type", "margin",
+ "margin-bottom", "margin-left", "margin-right", "margin-top",
+ "marks", "marquee-direction", "marquee-loop",
+ "marquee-play-count", "marquee-speed", "marquee-style", "max-height",
+ "max-width", "min-height", "min-width", "mix-blend-mode", "move-to", "nav-down", "nav-index",
+ "nav-left", "nav-right", "nav-up", "object-fit", "object-position",
+ "opacity", "order", "orphans", "outline",
+ "outline-color", "outline-offset", "outline-style", "outline-width",
+ "overflow", "overflow-style", "overflow-wrap", "overflow-x", "overflow-y",
+ "padding", "padding-bottom", "padding-left", "padding-right", "padding-top",
+ "page", "page-break-after", "page-break-before", "page-break-inside",
+ "page-policy", "pause", "pause-after", "pause-before", "perspective",
+ "perspective-origin", "pitch", "pitch-range", "place-content", "place-items", "place-self", "play-during", "position",
+ "presentation-level", "punctuation-trim", "quotes", "region-break-after",
+ "region-break-before", "region-break-inside", "region-fragment",
+ "rendering-intent", "resize", "rest", "rest-after", "rest-before", "richness",
+ "right", "rotation", "rotation-point", "ruby-align", "ruby-overhang",
+ "ruby-position", "ruby-span", "shape-image-threshold", "shape-inside", "shape-margin",
+ "shape-outside", "size", "speak", "speak-as", "speak-header",
+ "speak-numeral", "speak-punctuation", "speech-rate", "stress", "string-set",
+ "tab-size", "table-layout", "target", "target-name", "target-new",
+ "target-position", "text-align", "text-align-last", "text-decoration",
+ "text-decoration-color", "text-decoration-line", "text-decoration-skip",
+ "text-decoration-style", "text-emphasis", "text-emphasis-color",
+ "text-emphasis-position", "text-emphasis-style", "text-height",
+ "text-indent", "text-justify", "text-outline", "text-overflow", "text-shadow",
+ "text-size-adjust", "text-space-collapse", "text-transform", "text-underline-position",
+ "text-wrap", "top", "transform", "transform-origin", "transform-style",
+ "transition", "transition-delay", "transition-duration",
+ "transition-property", "transition-timing-function", "unicode-bidi",
+ "user-select", "vertical-align", "visibility", "voice-balance", "voice-duration",
+ "voice-family", "voice-pitch", "voice-range", "voice-rate", "voice-stress",
+ "voice-volume", "volume", "white-space", "widows", "width", "will-change", "word-break",
+ "word-spacing", "word-wrap", "z-index",
+ // SVG-specific
+ "clip-path", "clip-rule", "mask", "enable-background", "filter", "flood-color",
+ "flood-opacity", "lighting-color", "stop-color", "stop-opacity", "pointer-events",
+ "color-interpolation", "color-interpolation-filters",
+ "color-rendering", "fill", "fill-opacity", "fill-rule", "image-rendering",
+ "marker", "marker-end", "marker-mid", "marker-start", "shape-rendering", "stroke",
+ "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin",
+ "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-rendering",
+ "baseline-shift", "dominant-baseline", "glyph-orientation-horizontal",
+ "glyph-orientation-vertical", "text-anchor", "writing-mode"
+ ], propertyKeywords = keySet(propertyKeywords_);
+
+ var nonStandardPropertyKeywords_ = [
+ "scrollbar-arrow-color", "scrollbar-base-color", "scrollbar-dark-shadow-color",
+ "scrollbar-face-color", "scrollbar-highlight-color", "scrollbar-shadow-color",
+ "scrollbar-3d-light-color", "scrollbar-track-color", "shape-inside",
+ "searchfield-cancel-button", "searchfield-decoration", "searchfield-results-button",
+ "searchfield-results-decoration", "zoom"
+ ], nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_);
+
+ var fontProperties_ = [
+ "font-family", "src", "unicode-range", "font-variant", "font-feature-settings",
+ "font-stretch", "font-weight", "font-style"
+ ], fontProperties = keySet(fontProperties_);
+
+ var counterDescriptors_ = [
+ "additive-symbols", "fallback", "negative", "pad", "prefix", "range",
+ "speak-as", "suffix", "symbols", "system"
+ ], counterDescriptors = keySet(counterDescriptors_);
+
+ var colorKeywords_ = [
+ "aliceblue", "antiquewhite", "aqua", "aquamarine", "azure", "beige",
+ "bisque", "black", "blanchedalmond", "blue", "blueviolet", "brown",
+ "burlywood", "cadetblue", "chartreuse", "chocolate", "coral", "cornflowerblue",
+ "cornsilk", "crimson", "cyan", "darkblue", "darkcyan", "darkgoldenrod",
+ "darkgray", "darkgreen", "darkkhaki", "darkmagenta", "darkolivegreen",
+ "darkorange", "darkorchid", "darkred", "darksalmon", "darkseagreen",
+ "darkslateblue", "darkslategray", "darkturquoise", "darkviolet",
+ "deeppink", "deepskyblue", "dimgray", "dodgerblue", "firebrick",
+ "floralwhite", "forestgreen", "fuchsia", "gainsboro", "ghostwhite",
+ "gold", "goldenrod", "gray", "grey", "green", "greenyellow", "honeydew",
+ "hotpink", "indianred", "indigo", "ivory", "khaki", "lavender",
+ "lavenderblush", "lawngreen", "lemonchiffon", "lightblue", "lightcoral",
+ "lightcyan", "lightgoldenrodyellow", "lightgray", "lightgreen", "lightpink",
+ "lightsalmon", "lightseagreen", "lightskyblue", "lightslategray",
+ "lightsteelblue", "lightyellow", "lime", "limegreen", "linen", "magenta",
+ "maroon", "mediumaquamarine", "mediumblue", "mediumorchid", "mediumpurple",
+ "mediumseagreen", "mediumslateblue", "mediumspringgreen", "mediumturquoise",
+ "mediumvioletred", "midnightblue", "mintcream", "mistyrose", "moccasin",
+ "navajowhite", "navy", "oldlace", "olive", "olivedrab", "orange", "orangered",
+ "orchid", "palegoldenrod", "palegreen", "paleturquoise", "palevioletred",
+ "papayawhip", "peachpuff", "peru", "pink", "plum", "powderblue",
+ "purple", "rebeccapurple", "red", "rosybrown", "royalblue", "saddlebrown",
+ "salmon", "sandybrown", "seagreen", "seashell", "sienna", "silver", "skyblue",
+ "slateblue", "slategray", "snow", "springgreen", "steelblue", "tan",
+ "teal", "thistle", "tomato", "turquoise", "violet", "wheat", "white",
+ "whitesmoke", "yellow", "yellowgreen"
+ ], colorKeywords = keySet(colorKeywords_);
+
+ var valueKeywords_ = [
+ "above", "absolute", "activeborder", "additive", "activecaption", "afar",
+ "after-white-space", "ahead", "alias", "all", "all-scroll", "alphabetic", "alternate",
+ "always", "amharic", "amharic-abegede", "antialiased", "appworkspace",
+ "arabic-indic", "armenian", "asterisks", "attr", "auto", "auto-flow", "avoid", "avoid-column", "avoid-page",
+ "avoid-region", "background", "backwards", "baseline", "below", "bidi-override", "binary",
+ "bengali", "blink", "block", "block-axis", "bold", "bolder", "border", "border-box",
+ "both", "bottom", "break", "break-all", "break-word", "bullets", "button", "button-bevel",
+ "buttonface", "buttonhighlight", "buttonshadow", "buttontext", "calc", "cambodian",
+ "capitalize", "caps-lock-indicator", "caption", "captiontext", "caret",
+ "cell", "center", "checkbox", "circle", "cjk-decimal", "cjk-earthly-branch",
+ "cjk-heavenly-stem", "cjk-ideographic", "clear", "clip", "close-quote",
+ "col-resize", "collapse", "color", "color-burn", "color-dodge", "column", "column-reverse",
+ "compact", "condensed", "contain", "content", "contents",
+ "content-box", "context-menu", "continuous", "copy", "counter", "counters", "cover", "crop",
+ "cross", "crosshair", "currentcolor", "cursive", "cyclic", "darken", "dashed", "decimal",
+ "decimal-leading-zero", "default", "default-button", "dense", "destination-atop",
+ "destination-in", "destination-out", "destination-over", "devanagari", "difference",
+ "disc", "discard", "disclosure-closed", "disclosure-open", "document",
+ "dot-dash", "dot-dot-dash",
+ "dotted", "double", "down", "e-resize", "ease", "ease-in", "ease-in-out", "ease-out",
+ "element", "ellipse", "ellipsis", "embed", "end", "ethiopic", "ethiopic-abegede",
+ "ethiopic-abegede-am-et", "ethiopic-abegede-gez", "ethiopic-abegede-ti-er",
+ "ethiopic-abegede-ti-et", "ethiopic-halehame-aa-er",
+ "ethiopic-halehame-aa-et", "ethiopic-halehame-am-et",
+ "ethiopic-halehame-gez", "ethiopic-halehame-om-et",
+ "ethiopic-halehame-sid-et", "ethiopic-halehame-so-et",
+ "ethiopic-halehame-ti-er", "ethiopic-halehame-ti-et", "ethiopic-halehame-tig",
+ "ethiopic-numeric", "ew-resize", "exclusion", "expanded", "extends", "extra-condensed",
+ "extra-expanded", "fantasy", "fast", "fill", "fixed", "flat", "flex", "flex-end", "flex-start", "footnotes",
+ "forwards", "from", "geometricPrecision", "georgian", "graytext", "grid", "groove",
+ "gujarati", "gurmukhi", "hand", "hangul", "hangul-consonant", "hard-light", "hebrew",
+ "help", "hidden", "hide", "higher", "highlight", "highlighttext",
+ "hiragana", "hiragana-iroha", "horizontal", "hsl", "hsla", "hue", "hwb", "icon", "ignore",
+ "inactiveborder", "inactivecaption", "inactivecaptiontext", "infinite",
+ "infobackground", "infotext", "inherit", "initial", "inline", "inline-axis",
+ "inline-block", "inline-flex", "inline-grid", "inline-table", "inset", "inside", "intrinsic", "invert",
+ "italic", "japanese-formal", "japanese-informal", "justify", "kannada",
+ "katakana", "katakana-iroha", "keep-all", "khmer",
+ "korean-hangul-formal", "korean-hanja-formal", "korean-hanja-informal",
+ "landscape", "lao", "large", "larger", "left", "level", "lighter", "lighten",
+ "line-through", "linear", "linear-gradient", "lines", "list-item", "listbox", "listitem",
+ "local", "logical", "loud", "lower", "lower-alpha", "lower-armenian",
+ "lower-greek", "lower-hexadecimal", "lower-latin", "lower-norwegian",
+ "lower-roman", "lowercase", "ltr", "luminosity", "malayalam", "match", "matrix", "matrix3d",
+ "media-controls-background", "media-current-time-display",
+ "media-fullscreen-button", "media-mute-button", "media-play-button",
+ "media-return-to-realtime-button", "media-rewind-button",
+ "media-seek-back-button", "media-seek-forward-button", "media-slider",
+ "media-sliderthumb", "media-time-remaining-display", "media-volume-slider",
+ "media-volume-slider-container", "media-volume-sliderthumb", "medium",
+ "menu", "menulist", "menulist-button", "menulist-text",
+ "menulist-textfield", "menutext", "message-box", "middle", "min-intrinsic",
+ "mix", "mongolian", "monospace", "move", "multiple", "multiply", "myanmar", "n-resize",
+ "narrower", "ne-resize", "nesw-resize", "no-close-quote", "no-drop",
+ "no-open-quote", "no-repeat", "none", "normal", "not-allowed", "nowrap",
+ "ns-resize", "numbers", "numeric", "nw-resize", "nwse-resize", "oblique", "octal", "opacity", "open-quote",
+ "optimizeLegibility", "optimizeSpeed", "oriya", "oromo", "outset",
+ "outside", "outside-shape", "overlay", "overline", "padding", "padding-box",
+ "painted", "page", "paused", "persian", "perspective", "plus-darker", "plus-lighter",
+ "pointer", "polygon", "portrait", "pre", "pre-line", "pre-wrap", "preserve-3d",
+ "progress", "push-button", "radial-gradient", "radio", "read-only",
+ "read-write", "read-write-plaintext-only", "rectangle", "region",
+ "relative", "repeat", "repeating-linear-gradient",
+ "repeating-radial-gradient", "repeat-x", "repeat-y", "reset", "reverse",
+ "rgb", "rgba", "ridge", "right", "rotate", "rotate3d", "rotateX", "rotateY",
+ "rotateZ", "round", "row", "row-resize", "row-reverse", "rtl", "run-in", "running",
+ "s-resize", "sans-serif", "saturation", "scale", "scale3d", "scaleX", "scaleY", "scaleZ", "screen",
+ "scroll", "scrollbar", "scroll-position", "se-resize", "searchfield",
+ "searchfield-cancel-button", "searchfield-decoration",
+ "searchfield-results-button", "searchfield-results-decoration", "self-start", "self-end",
+ "semi-condensed", "semi-expanded", "separate", "serif", "show", "sidama",
+ "simp-chinese-formal", "simp-chinese-informal", "single",
+ "skew", "skewX", "skewY", "skip-white-space", "slide", "slider-horizontal",
+ "slider-vertical", "sliderthumb-horizontal", "sliderthumb-vertical", "slow",
+ "small", "small-caps", "small-caption", "smaller", "soft-light", "solid", "somali",
+ "source-atop", "source-in", "source-out", "source-over", "space", "space-around", "space-between", "space-evenly", "spell-out", "square",
+ "square-button", "start", "static", "status-bar", "stretch", "stroke", "sub",
+ "subpixel-antialiased", "super", "sw-resize", "symbolic", "symbols", "system-ui", "table",
+ "table-caption", "table-cell", "table-column", "table-column-group",
+ "table-footer-group", "table-header-group", "table-row", "table-row-group",
+ "tamil",
+ "telugu", "text", "text-bottom", "text-top", "textarea", "textfield", "thai",
+ "thick", "thin", "threeddarkshadow", "threedface", "threedhighlight",
+ "threedlightshadow", "threedshadow", "tibetan", "tigre", "tigrinya-er",
+ "tigrinya-er-abegede", "tigrinya-et", "tigrinya-et-abegede", "to", "top",
+ "trad-chinese-formal", "trad-chinese-informal", "transform",
+ "translate", "translate3d", "translateX", "translateY", "translateZ",
+ "transparent", "ultra-condensed", "ultra-expanded", "underline", "unset", "up",
+ "upper-alpha", "upper-armenian", "upper-greek", "upper-hexadecimal",
+ "upper-latin", "upper-norwegian", "upper-roman", "uppercase", "urdu", "url",
+ "var", "vertical", "vertical-text", "visible", "visibleFill", "visiblePainted",
+ "visibleStroke", "visual", "w-resize", "wait", "wave", "wider",
+ "window", "windowframe", "windowtext", "words", "wrap", "wrap-reverse", "x-large", "x-small", "xor",
+ "xx-large", "xx-small"
+ ], valueKeywords = keySet(valueKeywords_);
+
+ var allWords = documentTypes_.concat(mediaTypes_).concat(mediaFeatures_).concat(mediaValueKeywords_)
+ .concat(propertyKeywords_).concat(nonStandardPropertyKeywords_).concat(colorKeywords_)
+ .concat(valueKeywords_);
+ CodeMirror.registerHelper("hintWords", "css", allWords);
+
+ function tokenCComment(stream, state) {
+ var maybeEnd = false, ch;
+ while ((ch = stream.next()) != null) {
+ if (maybeEnd && ch == "/") {
+ state.tokenize = null;
+ break;
+ }
+ maybeEnd = (ch == "*");
+ }
+ return ["comment", "comment"];
+ }
+
+ CodeMirror.defineMIME("text/css", {
+ documentTypes: documentTypes,
+ mediaTypes: mediaTypes,
+ mediaFeatures: mediaFeatures,
+ mediaValueKeywords: mediaValueKeywords,
+ propertyKeywords: propertyKeywords,
+ nonStandardPropertyKeywords: nonStandardPropertyKeywords,
+ fontProperties: fontProperties,
+ counterDescriptors: counterDescriptors,
+ colorKeywords: colorKeywords,
+ valueKeywords: valueKeywords,
+ tokenHooks: {
+ "/": function(stream, state) {
+ if (!stream.eat("*")) return false;
+ state.tokenize = tokenCComment;
+ return tokenCComment(stream, state);
+ }
+ },
+ name: "css"
+ });
+
+ CodeMirror.defineMIME("text/x-scss", {
+ mediaTypes: mediaTypes,
+ mediaFeatures: mediaFeatures,
+ mediaValueKeywords: mediaValueKeywords,
+ propertyKeywords: propertyKeywords,
+ nonStandardPropertyKeywords: nonStandardPropertyKeywords,
+ colorKeywords: colorKeywords,
+ valueKeywords: valueKeywords,
+ fontProperties: fontProperties,
+ allowNested: true,
+ lineComment: "//",
+ tokenHooks: {
+ "/": function(stream, state) {
+ if (stream.eat("/")) {
+ stream.skipToEnd();
+ return ["comment", "comment"];
+ } else if (stream.eat("*")) {
+ state.tokenize = tokenCComment;
+ return tokenCComment(stream, state);
+ } else {
+ return ["operator", "operator"];
+ }
+ },
+ ":": function(stream) {
+ if (stream.match(/\s*\{/, false))
+ return [null, null]
+ return false;
+ },
+ "$": function(stream) {
+ stream.match(/^[\w-]+/);
+ if (stream.match(/^\s*:/, false))
+ return ["variable-2", "variable-definition"];
+ return ["variable-2", "variable"];
+ },
+ "#": function(stream) {
+ if (!stream.eat("{")) return false;
+ return [null, "interpolation"];
+ }
+ },
+ name: "css",
+ helperType: "scss"
+ });
+
+ CodeMirror.defineMIME("text/x-less", {
+ mediaTypes: mediaTypes,
+ mediaFeatures: mediaFeatures,
+ mediaValueKeywords: mediaValueKeywords,
+ propertyKeywords: propertyKeywords,
+ nonStandardPropertyKeywords: nonStandardPropertyKeywords,
+ colorKeywords: colorKeywords,
+ valueKeywords: valueKeywords,
+ fontProperties: fontProperties,
+ allowNested: true,
+ lineComment: "//",
+ tokenHooks: {
+ "/": function(stream, state) {
+ if (stream.eat("/")) {
+ stream.skipToEnd();
+ return ["comment", "comment"];
+ } else if (stream.eat("*")) {
+ state.tokenize = tokenCComment;
+ return tokenCComment(stream, state);
+ } else {
+ return ["operator", "operator"];
+ }
+ },
+ "@": function(stream) {
+ if (stream.eat("{")) return [null, "interpolation"];
+ if (stream.match(/^(charset|document|font-face|import|(-(moz|ms|o|webkit)-)?keyframes|media|namespace|page|supports)\b/i, false)) return false;
+ stream.eatWhile(/[\w\\\-]/);
+ if (stream.match(/^\s*:/, false))
+ return ["variable-2", "variable-definition"];
+ return ["variable-2", "variable"];
+ },
+ "&": function() {
+ return ["atom", "atom"];
+ }
+ },
+ name: "css",
+ helperType: "less"
+ });
+
+ CodeMirror.defineMIME("text/x-gss", {
+ documentTypes: documentTypes,
+ mediaTypes: mediaTypes,
+ mediaFeatures: mediaFeatures,
+ propertyKeywords: propertyKeywords,
+ nonStandardPropertyKeywords: nonStandardPropertyKeywords,
+ fontProperties: fontProperties,
+ counterDescriptors: counterDescriptors,
+ colorKeywords: colorKeywords,
+ valueKeywords: valueKeywords,
+ supportsAtComponent: true,
+ tokenHooks: {
+ "/": function(stream, state) {
+ if (!stream.eat("*")) return false;
+ state.tokenize = tokenCComment;
+ return tokenCComment(stream, state);
+ }
+ },
+ name: "css",
+ helperType: "gss"
+ });
+
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/mode/elm/elm.js b/devtools/client/shared/sourceeditor/codemirror/mode/elm/elm.js
new file mode 100644
index 0000000000..d51d0f6467
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/mode/elm/elm.js
@@ -0,0 +1,205 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ CodeMirror.defineMode("elm", function() {
+
+ function switchState(source, setState, f) {
+ setState(f);
+ return f(source, setState);
+ }
+
+ // These should all be Unicode extended, as per the Haskell 2010 report
+ var smallRE = /[a-z_]/;
+ var largeRE = /[A-Z]/;
+ var digitRE = /[0-9]/;
+ var hexitRE = /[0-9A-Fa-f]/;
+ var octitRE = /[0-7]/;
+ var idRE = /[a-z_A-Z0-9\']/;
+ var symbolRE = /[-!#$%&*+.\/<=>?@\\^|~:\u03BB\u2192]/;
+ var specialRE = /[(),;[\]`{}]/;
+ var whiteCharRE = /[ \t\v\f]/; // newlines are handled in tokenizer
+
+ function normal() {
+ return function (source, setState) {
+ if (source.eatWhile(whiteCharRE)) {
+ return null;
+ }
+
+ var ch = source.next();
+ if (specialRE.test(ch)) {
+ if (ch == '{' && source.eat('-')) {
+ var t = "comment";
+ if (source.eat('#')) t = "meta";
+ return switchState(source, setState, ncomment(t, 1));
+ }
+ return null;
+ }
+
+ if (ch == '\'') {
+ if (source.eat('\\'))
+ source.next(); // should handle other escapes here
+ else
+ source.next();
+
+ if (source.eat('\''))
+ return "string";
+ return "error";
+ }
+
+ if (ch == '"') {
+ return switchState(source, setState, stringLiteral);
+ }
+
+ if (largeRE.test(ch)) {
+ source.eatWhile(idRE);
+ if (source.eat('.'))
+ return "qualifier";
+ return "variable-2";
+ }
+
+ if (smallRE.test(ch)) {
+ var isDef = source.pos === 1;
+ source.eatWhile(idRE);
+ return isDef ? "type" : "variable";
+ }
+
+ if (digitRE.test(ch)) {
+ if (ch == '0') {
+ if (source.eat(/[xX]/)) {
+ source.eatWhile(hexitRE); // should require at least 1
+ return "integer";
+ }
+ if (source.eat(/[oO]/)) {
+ source.eatWhile(octitRE); // should require at least 1
+ return "number";
+ }
+ }
+ source.eatWhile(digitRE);
+ var t = "number";
+ if (source.eat('.')) {
+ t = "number";
+ source.eatWhile(digitRE); // should require at least 1
+ }
+ if (source.eat(/[eE]/)) {
+ t = "number";
+ source.eat(/[-+]/);
+ source.eatWhile(digitRE); // should require at least 1
+ }
+ return t;
+ }
+
+ if (symbolRE.test(ch)) {
+ if (ch == '-' && source.eat(/-/)) {
+ source.eatWhile(/-/);
+ if (!source.eat(symbolRE)) {
+ source.skipToEnd();
+ return "comment";
+ }
+ }
+ source.eatWhile(symbolRE);
+ return "builtin";
+ }
+
+ return "error";
+ }
+ }
+
+ function ncomment(type, nest) {
+ if (nest == 0) {
+ return normal();
+ }
+ return function(source, setState) {
+ var currNest = nest;
+ while (!source.eol()) {
+ var ch = source.next();
+ if (ch == '{' && source.eat('-')) {
+ ++currNest;
+ } else if (ch == '-' && source.eat('}')) {
+ --currNest;
+ if (currNest == 0) {
+ setState(normal());
+ return type;
+ }
+ }
+ }
+ setState(ncomment(type, currNest));
+ return type;
+ }
+ }
+
+ function stringLiteral(source, setState) {
+ while (!source.eol()) {
+ var ch = source.next();
+ if (ch == '"') {
+ setState(normal());
+ return "string";
+ }
+ if (ch == '\\') {
+ if (source.eol() || source.eat(whiteCharRE)) {
+ setState(stringGap);
+ return "string";
+ }
+ if (!source.eat('&')) source.next(); // should handle other escapes here
+ }
+ }
+ setState(normal());
+ return "error";
+ }
+
+ function stringGap(source, setState) {
+ if (source.eat('\\')) {
+ return switchState(source, setState, stringLiteral);
+ }
+ source.next();
+ setState(normal());
+ return "error";
+ }
+
+
+ var wellKnownWords = (function() {
+ var wkw = {};
+
+ var keywords = [
+ "case", "of", "as",
+ "if", "then", "else",
+ "let", "in",
+ "infix", "infixl", "infixr",
+ "type", "alias",
+ "input", "output", "foreign", "loopback",
+ "module", "where", "import", "exposing",
+ "_", "..", "|", ":", "=", "\\", "\"", "->", "<-"
+ ];
+
+ for (var i = keywords.length; i--;)
+ wkw[keywords[i]] = "keyword";
+
+ return wkw;
+ })();
+
+
+
+ return {
+ startState: function () { return { f: normal() }; },
+ copyState: function (s) { return { f: s.f }; },
+
+ token: function(stream, state) {
+ var t = state.f(stream, function(s) { state.f = s; });
+ var w = stream.current();
+ return (wellKnownWords.hasOwnProperty(w)) ? wellKnownWords[w] : t;
+ }
+ };
+
+ });
+
+ CodeMirror.defineMIME("text/x-elm", "elm");
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/mode/haxe/haxe.js b/devtools/client/shared/sourceeditor/codemirror/mode/haxe/haxe.js
new file mode 100644
index 0000000000..8ddf420a68
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/mode/haxe/haxe.js
@@ -0,0 +1,515 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+"use strict";
+
+CodeMirror.defineMode("haxe", function(config, parserConfig) {
+ var indentUnit = config.indentUnit;
+
+ // Tokenizer
+
+ function kw(type) {return {type: type, style: "keyword"};}
+ var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c");
+ var operator = kw("operator"), atom = {type: "atom", style: "atom"}, attribute = {type:"attribute", style: "attribute"};
+ var type = kw("typedef");
+ var keywords = {
+ "if": A, "while": A, "else": B, "do": B, "try": B,
+ "return": C, "break": C, "continue": C, "new": C, "throw": C,
+ "var": kw("var"), "inline":attribute, "static": attribute, "using":kw("import"),
+ "public": attribute, "private": attribute, "cast": kw("cast"), "import": kw("import"), "macro": kw("macro"),
+ "function": kw("function"), "catch": kw("catch"), "untyped": kw("untyped"), "callback": kw("cb"),
+ "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
+ "in": operator, "never": kw("property_access"), "trace":kw("trace"),
+ "class": type, "abstract":type, "enum":type, "interface":type, "typedef":type, "extends":type, "implements":type, "dynamic":type,
+ "true": atom, "false": atom, "null": atom
+ };
+
+ var isOperatorChar = /[+\-*&%=<>!?|]/;
+
+ function chain(stream, state, f) {
+ state.tokenize = f;
+ return f(stream, state);
+ }
+
+ function toUnescaped(stream, end) {
+ var escaped = false, next;
+ while ((next = stream.next()) != null) {
+ if (next == end && !escaped)
+ return true;
+ escaped = !escaped && next == "\\";
+ }
+ }
+
+ // Used as scratch variables to communicate multiple values without
+ // consing up tons of objects.
+ var type, content;
+ function ret(tp, style, cont) {
+ type = tp; content = cont;
+ return style;
+ }
+
+ function haxeTokenBase(stream, state) {
+ var ch = stream.next();
+ if (ch == '"' || ch == "'") {
+ return chain(stream, state, haxeTokenString(ch));
+ } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
+ return ret(ch);
+ } else if (ch == "0" && stream.eat(/x/i)) {
+ stream.eatWhile(/[\da-f]/i);
+ return ret("number", "number");
+ } else if (/\d/.test(ch) || ch == "-" && stream.eat(/\d/)) {
+ stream.match(/^\d*(?:\.\d*(?!\.))?(?:[eE][+\-]?\d+)?/);
+ return ret("number", "number");
+ } else if (state.reAllowed && (ch == "~" && stream.eat(/\//))) {
+ toUnescaped(stream, "/");
+ stream.eatWhile(/[gimsu]/);
+ return ret("regexp", "string-2");
+ } else if (ch == "/") {
+ if (stream.eat("*")) {
+ return chain(stream, state, haxeTokenComment);
+ } else if (stream.eat("/")) {
+ stream.skipToEnd();
+ return ret("comment", "comment");
+ } else {
+ stream.eatWhile(isOperatorChar);
+ return ret("operator", null, stream.current());
+ }
+ } else if (ch == "#") {
+ stream.skipToEnd();
+ return ret("conditional", "meta");
+ } else if (ch == "@") {
+ stream.eat(/:/);
+ stream.eatWhile(/[\w_]/);
+ return ret ("metadata", "meta");
+ } else if (isOperatorChar.test(ch)) {
+ stream.eatWhile(isOperatorChar);
+ return ret("operator", null, stream.current());
+ } else {
+ var word;
+ if(/[A-Z]/.test(ch)) {
+ stream.eatWhile(/[\w_<>]/);
+ word = stream.current();
+ return ret("type", "variable-3", word);
+ } else {
+ stream.eatWhile(/[\w_]/);
+ var word = stream.current(), known = keywords.propertyIsEnumerable(word) && keywords[word];
+ return (known && state.kwAllowed) ? ret(known.type, known.style, word) :
+ ret("variable", "variable", word);
+ }
+ }
+ }
+
+ function haxeTokenString(quote) {
+ return function(stream, state) {
+ if (toUnescaped(stream, quote))
+ state.tokenize = haxeTokenBase;
+ return ret("string", "string");
+ };
+ }
+
+ function haxeTokenComment(stream, state) {
+ var maybeEnd = false, ch;
+ while (ch = stream.next()) {
+ if (ch == "/" && maybeEnd) {
+ state.tokenize = haxeTokenBase;
+ break;
+ }
+ maybeEnd = (ch == "*");
+ }
+ return ret("comment", "comment");
+ }
+
+ // Parser
+
+ var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true};
+
+ function HaxeLexical(indented, column, type, align, prev, info) {
+ this.indented = indented;
+ this.column = column;
+ this.type = type;
+ this.prev = prev;
+ this.info = info;
+ if (align != null) this.align = align;
+ }
+
+ function inScope(state, varname) {
+ for (var v = state.localVars; v; v = v.next)
+ if (v.name == varname) return true;
+ }
+
+ function parseHaxe(state, style, type, content, stream) {
+ var cc = state.cc;
+ // Communicate our context to the combinators.
+ // (Less wasteful than consing up a hundred closures on every call.)
+ cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc;
+
+ if (!state.lexical.hasOwnProperty("align"))
+ state.lexical.align = true;
+
+ while(true) {
+ var combinator = cc.length ? cc.pop() : statement;
+ if (combinator(type, content)) {
+ while(cc.length && cc[cc.length - 1].lex)
+ cc.pop()();
+ if (cx.marked) return cx.marked;
+ if (type == "variable" && inScope(state, content)) return "variable-2";
+ if (type == "variable" && imported(state, content)) return "variable-3";
+ return style;
+ }
+ }
+ }
+
+ function imported(state, typename) {
+ if (/[a-z]/.test(typename.charAt(0)))
+ return false;
+ var len = state.importedtypes.length;
+ for (var i = 0; i<len; i++)
+ if(state.importedtypes[i]==typename) return true;
+ }
+
+ function registerimport(importname) {
+ var state = cx.state;
+ for (var t = state.importedtypes; t; t = t.next)
+ if(t.name == importname) return;
+ state.importedtypes = { name: importname, next: state.importedtypes };
+ }
+ // Combinator utils
+
+ var cx = {state: null, column: null, marked: null, cc: null};
+ function pass() {
+ for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
+ }
+ function cont() {
+ pass.apply(null, arguments);
+ return true;
+ }
+ function inList(name, list) {
+ for (var v = list; v; v = v.next)
+ if (v.name == name) return true;
+ return false;
+ }
+ function register(varname) {
+ var state = cx.state;
+ if (state.context) {
+ cx.marked = "def";
+ if (inList(varname, state.localVars)) return;
+ state.localVars = {name: varname, next: state.localVars};
+ } else if (state.globalVars) {
+ if (inList(varname, state.globalVars)) return;
+ state.globalVars = {name: varname, next: state.globalVars};
+ }
+ }
+
+ // Combinators
+
+ var defaultVars = {name: "this", next: null};
+ function pushcontext() {
+ if (!cx.state.context) cx.state.localVars = defaultVars;
+ cx.state.context = {prev: cx.state.context, vars: cx.state.localVars};
+ }
+ function popcontext() {
+ cx.state.localVars = cx.state.context.vars;
+ cx.state.context = cx.state.context.prev;
+ }
+ popcontext.lex = true;
+ function pushlex(type, info) {
+ var result = function() {
+ var state = cx.state;
+ state.lexical = new HaxeLexical(state.indented, cx.stream.column(), type, null, state.lexical, info);
+ };
+ result.lex = true;
+ return result;
+ }
+ function poplex() {
+ var state = cx.state;
+ if (state.lexical.prev) {
+ if (state.lexical.type == ")")
+ state.indented = state.lexical.indented;
+ state.lexical = state.lexical.prev;
+ }
+ }
+ poplex.lex = true;
+
+ function expect(wanted) {
+ function f(type) {
+ if (type == wanted) return cont();
+ else if (wanted == ";") return pass();
+ else return cont(f);
+ }
+ return f;
+ }
+
+ function statement(type) {
+ if (type == "@") return cont(metadef);
+ if (type == "var") return cont(pushlex("vardef"), vardef1, expect(";"), poplex);
+ if (type == "keyword a") return cont(pushlex("form"), expression, statement, poplex);
+ if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
+ if (type == "{") return cont(pushlex("}"), pushcontext, block, poplex, popcontext);
+ if (type == ";") return cont();
+ if (type == "attribute") return cont(maybeattribute);
+ if (type == "function") return cont(functiondef);
+ if (type == "for") return cont(pushlex("form"), expect("("), pushlex(")"), forspec1, expect(")"),
+ poplex, statement, poplex);
+ if (type == "variable") return cont(pushlex("stat"), maybelabel);
+ if (type == "switch") return cont(pushlex("form"), expression, pushlex("}", "switch"), expect("{"),
+ block, poplex, poplex);
+ if (type == "case") return cont(expression, expect(":"));
+ if (type == "default") return cont(expect(":"));
+ if (type == "catch") return cont(pushlex("form"), pushcontext, expect("("), funarg, expect(")"),
+ statement, poplex, popcontext);
+ if (type == "import") return cont(importdef, expect(";"));
+ if (type == "typedef") return cont(typedef);
+ return pass(pushlex("stat"), expression, expect(";"), poplex);
+ }
+ function expression(type) {
+ if (atomicTypes.hasOwnProperty(type)) return cont(maybeoperator);
+ if (type == "type" ) return cont(maybeoperator);
+ if (type == "function") return cont(functiondef);
+ if (type == "keyword c") return cont(maybeexpression);
+ if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeoperator);
+ if (type == "operator") return cont(expression);
+ if (type == "[") return cont(pushlex("]"), commasep(maybeexpression, "]"), poplex, maybeoperator);
+ if (type == "{") return cont(pushlex("}"), commasep(objprop, "}"), poplex, maybeoperator);
+ return cont();
+ }
+ function maybeexpression(type) {
+ if (type.match(/[;\}\)\],]/)) return pass();
+ return pass(expression);
+ }
+
+ function maybeoperator(type, value) {
+ if (type == "operator" && /\+\+|--/.test(value)) return cont(maybeoperator);
+ if (type == "operator" || type == ":") return cont(expression);
+ if (type == ";") return;
+ if (type == "(") return cont(pushlex(")"), commasep(expression, ")"), poplex, maybeoperator);
+ if (type == ".") return cont(property, maybeoperator);
+ if (type == "[") return cont(pushlex("]"), expression, expect("]"), poplex, maybeoperator);
+ }
+
+ function maybeattribute(type) {
+ if (type == "attribute") return cont(maybeattribute);
+ if (type == "function") return cont(functiondef);
+ if (type == "var") return cont(vardef1);
+ }
+
+ function metadef(type) {
+ if(type == ":") return cont(metadef);
+ if(type == "variable") return cont(metadef);
+ if(type == "(") return cont(pushlex(")"), commasep(metaargs, ")"), poplex, statement);
+ }
+ function metaargs(type) {
+ if(type == "variable") return cont();
+ }
+
+ function importdef (type, value) {
+ if(type == "variable" && /[A-Z]/.test(value.charAt(0))) { registerimport(value); return cont(); }
+ else if(type == "variable" || type == "property" || type == "." || value == "*") return cont(importdef);
+ }
+
+ function typedef (type, value)
+ {
+ if(type == "variable" && /[A-Z]/.test(value.charAt(0))) { registerimport(value); return cont(); }
+ else if (type == "type" && /[A-Z]/.test(value.charAt(0))) { return cont(); }
+ }
+
+ function maybelabel(type) {
+ if (type == ":") return cont(poplex, statement);
+ return pass(maybeoperator, expect(";"), poplex);
+ }
+ function property(type) {
+ if (type == "variable") {cx.marked = "property"; return cont();}
+ }
+ function objprop(type) {
+ if (type == "variable") cx.marked = "property";
+ if (atomicTypes.hasOwnProperty(type)) return cont(expect(":"), expression);
+ }
+ function commasep(what, end) {
+ function proceed(type) {
+ if (type == ",") return cont(what, proceed);
+ if (type == end) return cont();
+ return cont(expect(end));
+ }
+ return function(type) {
+ if (type == end) return cont();
+ else return pass(what, proceed);
+ };
+ }
+ function block(type) {
+ if (type == "}") return cont();
+ return pass(statement, block);
+ }
+ function vardef1(type, value) {
+ if (type == "variable"){register(value); return cont(typeuse, vardef2);}
+ return cont();
+ }
+ function vardef2(type, value) {
+ if (value == "=") return cont(expression, vardef2);
+ if (type == ",") return cont(vardef1);
+ }
+ function forspec1(type, value) {
+ if (type == "variable") {
+ register(value);
+ return cont(forin, expression)
+ } else {
+ return pass()
+ }
+ }
+ function forin(_type, value) {
+ if (value == "in") return cont();
+ }
+ function functiondef(type, value) {
+ //function names starting with upper-case letters are recognised as types, so cludging them together here.
+ if (type == "variable" || type == "type") {register(value); return cont(functiondef);}
+ if (value == "new") return cont(functiondef);
+ if (type == "(") return cont(pushlex(")"), pushcontext, commasep(funarg, ")"), poplex, typeuse, statement, popcontext);
+ }
+ function typeuse(type) {
+ if(type == ":") return cont(typestring);
+ }
+ function typestring(type) {
+ if(type == "type") return cont();
+ if(type == "variable") return cont();
+ if(type == "{") return cont(pushlex("}"), commasep(typeprop, "}"), poplex);
+ }
+ function typeprop(type) {
+ if(type == "variable") return cont(typeuse);
+ }
+ function funarg(type, value) {
+ if (type == "variable") {register(value); return cont(typeuse);}
+ }
+
+ // Interface
+ return {
+ startState: function(basecolumn) {
+ var defaulttypes = ["Int", "Float", "String", "Void", "Std", "Bool", "Dynamic", "Array"];
+ var state = {
+ tokenize: haxeTokenBase,
+ reAllowed: true,
+ kwAllowed: true,
+ cc: [],
+ lexical: new HaxeLexical((basecolumn || 0) - indentUnit, 0, "block", false),
+ localVars: parserConfig.localVars,
+ importedtypes: defaulttypes,
+ context: parserConfig.localVars && {vars: parserConfig.localVars},
+ indented: 0
+ };
+ if (parserConfig.globalVars && typeof parserConfig.globalVars == "object")
+ state.globalVars = parserConfig.globalVars;
+ return state;
+ },
+
+ token: function(stream, state) {
+ if (stream.sol()) {
+ if (!state.lexical.hasOwnProperty("align"))
+ state.lexical.align = false;
+ state.indented = stream.indentation();
+ }
+ if (stream.eatSpace()) return null;
+ var style = state.tokenize(stream, state);
+ if (type == "comment") return style;
+ state.reAllowed = !!(type == "operator" || type == "keyword c" || type.match(/^[\[{}\(,;:]$/));
+ state.kwAllowed = type != '.';
+ return parseHaxe(state, style, type, content, stream);
+ },
+
+ indent: function(state, textAfter) {
+ if (state.tokenize != haxeTokenBase) return 0;
+ var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical;
+ if (lexical.type == "stat" && firstChar == "}") lexical = lexical.prev;
+ var type = lexical.type, closing = firstChar == type;
+ if (type == "vardef") return lexical.indented + 4;
+ else if (type == "form" && firstChar == "{") return lexical.indented;
+ else if (type == "stat" || type == "form") return lexical.indented + indentUnit;
+ else if (lexical.info == "switch" && !closing)
+ return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
+ else if (lexical.align) return lexical.column + (closing ? 0 : 1);
+ else return lexical.indented + (closing ? 0 : indentUnit);
+ },
+
+ electricChars: "{}",
+ blockCommentStart: "/*",
+ blockCommentEnd: "*/",
+ lineComment: "//"
+ };
+});
+
+CodeMirror.defineMIME("text/x-haxe", "haxe");
+
+CodeMirror.defineMode("hxml", function () {
+
+ return {
+ startState: function () {
+ return {
+ define: false,
+ inString: false
+ };
+ },
+ token: function (stream, state) {
+ var ch = stream.peek();
+ var sol = stream.sol();
+
+ ///* comments */
+ if (ch == "#") {
+ stream.skipToEnd();
+ return "comment";
+ }
+ if (sol && ch == "-") {
+ var style = "variable-2";
+
+ stream.eat(/-/);
+
+ if (stream.peek() == "-") {
+ stream.eat(/-/);
+ style = "keyword a";
+ }
+
+ if (stream.peek() == "D") {
+ stream.eat(/[D]/);
+ style = "keyword c";
+ state.define = true;
+ }
+
+ stream.eatWhile(/[A-Z]/i);
+ return style;
+ }
+
+ var ch = stream.peek();
+
+ if (state.inString == false && ch == "'") {
+ state.inString = true;
+ stream.next();
+ }
+
+ if (state.inString == true) {
+ if (stream.skipTo("'")) {
+
+ } else {
+ stream.skipToEnd();
+ }
+
+ if (stream.peek() == "'") {
+ stream.next();
+ state.inString = false;
+ }
+
+ return "string";
+ }
+
+ stream.next();
+ return null;
+ },
+ lineComment: "#"
+ };
+});
+
+CodeMirror.defineMIME("text/x-hxml", "hxml");
+
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/mode/htmlmixed/htmlmixed.js b/devtools/client/shared/sourceeditor/codemirror/mode/htmlmixed/htmlmixed.js
new file mode 100644
index 0000000000..ca1bccdbdd
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/mode/htmlmixed/htmlmixed.js
@@ -0,0 +1,152 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"), require("resource://devtools/client/shared/sourceeditor/codemirror/mode/xml/xml.js"), require("resource://devtools/client/shared/sourceeditor/codemirror/mode/javascript/javascript.js"), require("resource://devtools/client/shared/sourceeditor/codemirror/mode/css/css.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror", "../xml/xml", "../javascript/javascript", "../css/css"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ var defaultTags = {
+ script: [
+ ["lang", /(javascript|babel)/i, "javascript"],
+ ["type", /^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i, "javascript"],
+ ["type", /./, "text/plain"],
+ [null, null, "javascript"]
+ ],
+ style: [
+ ["lang", /^css$/i, "css"],
+ ["type", /^(text\/)?(x-)?(stylesheet|css)$/i, "css"],
+ ["type", /./, "text/plain"],
+ [null, null, "css"]
+ ]
+ };
+
+ function maybeBackup(stream, pat, style) {
+ var cur = stream.current(), close = cur.search(pat);
+ if (close > -1) {
+ stream.backUp(cur.length - close);
+ } else if (cur.match(/<\/?$/)) {
+ stream.backUp(cur.length);
+ if (!stream.match(pat, false)) stream.match(cur);
+ }
+ return style;
+ }
+
+ var attrRegexpCache = {};
+ function getAttrRegexp(attr) {
+ var regexp = attrRegexpCache[attr];
+ if (regexp) return regexp;
+ return attrRegexpCache[attr] = new RegExp("\\s+" + attr + "\\s*=\\s*('|\")?([^'\"]+)('|\")?\\s*");
+ }
+
+ function getAttrValue(text, attr) {
+ var match = text.match(getAttrRegexp(attr))
+ return match ? /^\s*(.*?)\s*$/.exec(match[2])[1] : ""
+ }
+
+ function getTagRegexp(tagName, anchored) {
+ return new RegExp((anchored ? "^" : "") + "<\/\s*" + tagName + "\s*>", "i");
+ }
+
+ function addTags(from, to) {
+ for (var tag in from) {
+ var dest = to[tag] || (to[tag] = []);
+ var source = from[tag];
+ for (var i = source.length - 1; i >= 0; i--)
+ dest.unshift(source[i])
+ }
+ }
+
+ function findMatchingMode(tagInfo, tagText) {
+ for (var i = 0; i < tagInfo.length; i++) {
+ var spec = tagInfo[i];
+ if (!spec[0] || spec[1].test(getAttrValue(tagText, spec[0]))) return spec[2];
+ }
+ }
+
+ CodeMirror.defineMode("htmlmixed", function (config, parserConfig) {
+ var htmlMode = CodeMirror.getMode(config, {
+ name: "xml",
+ htmlMode: true,
+ multilineTagIndentFactor: parserConfig.multilineTagIndentFactor,
+ multilineTagIndentPastTag: parserConfig.multilineTagIndentPastTag
+ });
+
+ var tags = {};
+ var configTags = parserConfig && parserConfig.tags, configScript = parserConfig && parserConfig.scriptTypes;
+ addTags(defaultTags, tags);
+ if (configTags) addTags(configTags, tags);
+ if (configScript) for (var i = configScript.length - 1; i >= 0; i--)
+ tags.script.unshift(["type", configScript[i].matches, configScript[i].mode])
+
+ function html(stream, state) {
+ var style = htmlMode.token(stream, state.htmlState), tag = /\btag\b/.test(style), tagName
+ if (tag && !/[<>\s\/]/.test(stream.current()) &&
+ (tagName = state.htmlState.tagName && state.htmlState.tagName.toLowerCase()) &&
+ tags.hasOwnProperty(tagName)) {
+ state.inTag = tagName + " "
+ } else if (state.inTag && tag && />$/.test(stream.current())) {
+ var inTag = /^([\S]+) (.*)/.exec(state.inTag)
+ state.inTag = null
+ var modeSpec = stream.current() == ">" && findMatchingMode(tags[inTag[1]], inTag[2])
+ var mode = CodeMirror.getMode(config, modeSpec)
+ var endTagA = getTagRegexp(inTag[1], true), endTag = getTagRegexp(inTag[1], false);
+ state.token = function (stream, state) {
+ if (stream.match(endTagA, false)) {
+ state.token = html;
+ state.localState = state.localMode = null;
+ return null;
+ }
+ return maybeBackup(stream, endTag, state.localMode.token(stream, state.localState));
+ };
+ state.localMode = mode;
+ state.localState = CodeMirror.startState(mode, htmlMode.indent(state.htmlState, "", ""));
+ } else if (state.inTag) {
+ state.inTag += stream.current()
+ if (stream.eol()) state.inTag += " "
+ }
+ return style;
+ };
+
+ return {
+ startState: function () {
+ var state = CodeMirror.startState(htmlMode);
+ return {token: html, inTag: null, localMode: null, localState: null, htmlState: state};
+ },
+
+ copyState: function (state) {
+ var local;
+ if (state.localState) {
+ local = CodeMirror.copyState(state.localMode, state.localState);
+ }
+ return {token: state.token, inTag: state.inTag,
+ localMode: state.localMode, localState: local,
+ htmlState: CodeMirror.copyState(htmlMode, state.htmlState)};
+ },
+
+ token: function (stream, state) {
+ return state.token(stream, state);
+ },
+
+ indent: function (state, textAfter, line) {
+ if (!state.localMode || /^\s*<\//.test(textAfter))
+ return htmlMode.indent(state.htmlState, textAfter, line);
+ else if (state.localMode.indent)
+ return state.localMode.indent(state.localState, textAfter, line);
+ else
+ return CodeMirror.Pass;
+ },
+
+ innerMode: function (state) {
+ return {state: state.localState || state.htmlState, mode: state.localMode || htmlMode};
+ }
+ };
+ }, "xml", "javascript", "css");
+
+ CodeMirror.defineMIME("text/html", "htmlmixed");
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/mode/http/http.js b/devtools/client/shared/sourceeditor/codemirror/mode/http/http.js
new file mode 100644
index 0000000000..092353259f
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/mode/http/http.js
@@ -0,0 +1,113 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(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("http", function() {
+ function failFirstLine(stream, state) {
+ stream.skipToEnd();
+ state.cur = header;
+ return "error";
+ }
+
+ function start(stream, state) {
+ if (stream.match(/^HTTP\/\d\.\d/)) {
+ state.cur = responseStatusCode;
+ return "keyword";
+ } else if (stream.match(/^[A-Z]+/) && /[ \t]/.test(stream.peek())) {
+ state.cur = requestPath;
+ return "keyword";
+ } else {
+ return failFirstLine(stream, state);
+ }
+ }
+
+ function responseStatusCode(stream, state) {
+ var code = stream.match(/^\d+/);
+ if (!code) return failFirstLine(stream, state);
+
+ state.cur = responseStatusText;
+ var status = Number(code[0]);
+ if (status >= 100 && status < 200) {
+ return "positive informational";
+ } else if (status >= 200 && status < 300) {
+ return "positive success";
+ } else if (status >= 300 && status < 400) {
+ return "positive redirect";
+ } else if (status >= 400 && status < 500) {
+ return "negative client-error";
+ } else if (status >= 500 && status < 600) {
+ return "negative server-error";
+ } else {
+ return "error";
+ }
+ }
+
+ function responseStatusText(stream, state) {
+ stream.skipToEnd();
+ state.cur = header;
+ return null;
+ }
+
+ function requestPath(stream, state) {
+ stream.eatWhile(/\S/);
+ state.cur = requestProtocol;
+ return "string-2";
+ }
+
+ function requestProtocol(stream, state) {
+ if (stream.match(/^HTTP\/\d\.\d$/)) {
+ state.cur = header;
+ return "keyword";
+ } else {
+ return failFirstLine(stream, state);
+ }
+ }
+
+ function header(stream) {
+ if (stream.sol() && !stream.eat(/[ \t]/)) {
+ if (stream.match(/^.*?:/)) {
+ return "atom";
+ } else {
+ stream.skipToEnd();
+ return "error";
+ }
+ } else {
+ stream.skipToEnd();
+ return "string";
+ }
+ }
+
+ function body(stream) {
+ stream.skipToEnd();
+ return null;
+ }
+
+ return {
+ token: function(stream, state) {
+ var cur = state.cur;
+ if (cur != header && cur != body && stream.eatSpace()) return null;
+ return cur(stream, state);
+ },
+
+ blankLine: function(state) {
+ state.cur = body;
+ },
+
+ startState: function() {
+ return {cur: start};
+ }
+ };
+});
+
+CodeMirror.defineMIME("message/http", "http");
+
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/mode/javascript/javascript.js b/devtools/client/shared/sourceeditor/codemirror/mode/javascript/javascript.js
new file mode 100644
index 0000000000..a34b4f9bb9
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/mode/javascript/javascript.js
@@ -0,0 +1,934 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+"use strict";
+
+CodeMirror.defineMode("javascript", function(config, parserConfig) {
+ var indentUnit = config.indentUnit;
+ var statementIndent = parserConfig.statementIndent;
+ var jsonldMode = parserConfig.jsonld;
+ var jsonMode = parserConfig.json || jsonldMode;
+ var isTS = parserConfig.typescript;
+ var wordRE = parserConfig.wordCharacters || /[\w$\xa1-\uffff]/;
+
+ // Tokenizer
+
+ var keywords = function(){
+ function kw(type) {return {type: type, style: "keyword"};}
+ var A = kw("keyword a"), B = kw("keyword b"), C = kw("keyword c"), D = kw("keyword d");
+ var operator = kw("operator"), atom = {type: "atom", style: "atom"};
+
+ return {
+ "if": kw("if"), "while": A, "with": A, "else": B, "do": B, "try": B, "finally": B,
+ "return": D, "break": D, "continue": D, "new": kw("new"), "delete": C, "void": C, "throw": C,
+ "debugger": kw("debugger"), "var": kw("var"), "const": kw("var"), "let": kw("var"),
+ "function": kw("function"), "catch": kw("catch"),
+ "for": kw("for"), "switch": kw("switch"), "case": kw("case"), "default": kw("default"),
+ "in": operator, "typeof": operator, "instanceof": operator,
+ "true": atom, "false": atom, "null": atom, "undefined": atom, "NaN": atom, "Infinity": atom,
+ "this": kw("this"), "class": kw("class"), "super": kw("atom"),
+ "yield": C, "export": kw("export"), "import": kw("import"), "extends": C,
+ "await": C
+ };
+ }();
+
+ var isOperatorChar = /[+\-*&%=<>!?|~^@]/;
+ var isJsonldKeyword = /^@(context|id|value|language|type|container|list|set|reverse|index|base|vocab|graph)"/;
+
+ function readRegexp(stream) {
+ var escaped = false, next, inSet = false;
+ while ((next = stream.next()) != null) {
+ if (!escaped) {
+ if (next == "/" && !inSet) return;
+ if (next == "[") inSet = true;
+ else if (inSet && next == "]") inSet = false;
+ }
+ escaped = !escaped && next == "\\";
+ }
+ }
+
+ // Used as scratch variables to communicate multiple values without
+ // consing up tons of objects.
+ var type, content;
+ function ret(tp, style, cont) {
+ type = tp; content = cont;
+ return style;
+ }
+ function tokenBase(stream, state) {
+ var ch = stream.next();
+ if (ch == '"' || ch == "'") {
+ state.tokenize = tokenString(ch);
+ return state.tokenize(stream, state);
+ } else if (ch == "." && stream.match(/^\d[\d_]*(?:[eE][+\-]?[\d_]+)?/)) {
+ return ret("number", "number");
+ } else if (ch == "." && stream.match("..")) {
+ return ret("spread", "meta");
+ } else if (/[\[\]{}\(\),;\:\.]/.test(ch)) {
+ return ret(ch);
+ } else if (ch == "=" && stream.eat(">")) {
+ return ret("=>", "operator");
+ } else if (ch == "0" && stream.match(/^(?:x[\dA-Fa-f_]+|o[0-7_]+|b[01_]+)n?/)) {
+ return ret("number", "number");
+ } else if (/\d/.test(ch)) {
+ stream.match(/^[\d_]*(?:n|(?:\.[\d_]*)?(?:[eE][+\-]?[\d_]+)?)?/);
+ return ret("number", "number");
+ } else if (ch == "/") {
+ if (stream.eat("*")) {
+ state.tokenize = tokenComment;
+ return tokenComment(stream, state);
+ } else if (stream.eat("/")) {
+ stream.skipToEnd();
+ return ret("comment", "comment");
+ } else if (expressionAllowed(stream, state, 1)) {
+ readRegexp(stream);
+ stream.match(/^\b(([gimyus])(?![gimyus]*\2))+\b/);
+ return ret("regexp", "string-2");
+ } else {
+ stream.eat("=");
+ return ret("operator", "operator", stream.current());
+ }
+ } else if (ch == "`") {
+ state.tokenize = tokenQuasi;
+ return tokenQuasi(stream, state);
+ } else if (ch == "#" && stream.peek() == "!") {
+ stream.skipToEnd();
+ return ret("meta", "meta");
+ } else if (ch == "#" && stream.eatWhile(wordRE)) {
+ return ret("variable", "property")
+ } else if (ch == "<" && stream.match("!--") ||
+ (ch == "-" && stream.match("->") && !/\S/.test(stream.string.slice(0, stream.start)))) {
+ stream.skipToEnd()
+ return ret("comment", "comment")
+ } else if (isOperatorChar.test(ch)) {
+ if (ch != ">" || !state.lexical || state.lexical.type != ">") {
+ if (stream.eat("=")) {
+ if (ch == "!" || ch == "=") stream.eat("=")
+ } else if (/[<>*+\-|&?]/.test(ch)) {
+ stream.eat(ch)
+ if (ch == ">") stream.eat(ch)
+ }
+ }
+ if (ch == "?" && stream.eat(".")) return ret(".")
+ return ret("operator", "operator", stream.current());
+ } else if (wordRE.test(ch)) {
+ stream.eatWhile(wordRE);
+ var word = stream.current()
+ if (state.lastType != ".") {
+ if (keywords.propertyIsEnumerable(word)) {
+ var kw = keywords[word]
+ return ret(kw.type, kw.style, word)
+ }
+ if (word == "async" && stream.match(/^(\s|\/\*([^*]|\*(?!\/))*?\*\/)*[\[\(\w]/, false))
+ return ret("async", "keyword", word)
+ }
+ return ret("variable", "variable", word)
+ }
+ }
+
+ function tokenString(quote) {
+ return function(stream, state) {
+ var escaped = false, next;
+ if (jsonldMode && stream.peek() == "@" && stream.match(isJsonldKeyword)){
+ state.tokenize = tokenBase;
+ return ret("jsonld-keyword", "meta");
+ }
+ while ((next = stream.next()) != null) {
+ if (next == quote && !escaped) break;
+ escaped = !escaped && next == "\\";
+ }
+ if (!escaped) state.tokenize = tokenBase;
+ return ret("string", "string");
+ };
+ }
+
+ function tokenComment(stream, state) {
+ var maybeEnd = false, ch;
+ while (ch = stream.next()) {
+ if (ch == "/" && maybeEnd) {
+ state.tokenize = tokenBase;
+ break;
+ }
+ maybeEnd = (ch == "*");
+ }
+ return ret("comment", "comment");
+ }
+
+ function tokenQuasi(stream, state) {
+ var escaped = false, next;
+ while ((next = stream.next()) != null) {
+ if (!escaped && (next == "`" || next == "$" && stream.eat("{"))) {
+ state.tokenize = tokenBase;
+ break;
+ }
+ escaped = !escaped && next == "\\";
+ }
+ return ret("quasi", "string-2", stream.current());
+ }
+
+ var brackets = "([{}])";
+ // This is a crude lookahead trick to try and notice that we're
+ // parsing the argument patterns for a fat-arrow function before we
+ // actually hit the arrow token. It only works if the arrow is on
+ // the same line as the arguments and there's no strange noise
+ // (comments) in between. Fallback is to only notice when we hit the
+ // arrow, and not declare the arguments as locals for the arrow
+ // body.
+ function findFatArrow(stream, state) {
+ if (state.fatArrowAt) state.fatArrowAt = null;
+ var arrow = stream.string.indexOf("=>", stream.start);
+ if (arrow < 0) return;
+
+ if (isTS) { // Try to skip TypeScript return type declarations after the arguments
+ var m = /:\s*(?:\w+(?:<[^>]*>|\[\])?|\{[^}]*\})\s*$/.exec(stream.string.slice(stream.start, arrow))
+ if (m) arrow = m.index
+ }
+
+ var depth = 0, sawSomething = false;
+ for (var pos = arrow - 1; pos >= 0; --pos) {
+ var ch = stream.string.charAt(pos);
+ var bracket = brackets.indexOf(ch);
+ if (bracket >= 0 && bracket < 3) {
+ if (!depth) { ++pos; break; }
+ if (--depth == 0) { if (ch == "(") sawSomething = true; break; }
+ } else if (bracket >= 3 && bracket < 6) {
+ ++depth;
+ } else if (wordRE.test(ch)) {
+ sawSomething = true;
+ } else if (/["'\/`]/.test(ch)) {
+ for (;; --pos) {
+ if (pos == 0) return
+ var next = stream.string.charAt(pos - 1)
+ if (next == ch && stream.string.charAt(pos - 2) != "\\") { pos--; break }
+ }
+ } else if (sawSomething && !depth) {
+ ++pos;
+ break;
+ }
+ }
+ if (sawSomething && !depth) state.fatArrowAt = pos;
+ }
+
+ // Parser
+
+ var atomicTypes = {"atom": true, "number": true, "variable": true, "string": true, "regexp": true, "this": true, "jsonld-keyword": true};
+
+ function JSLexical(indented, column, type, align, prev, info) {
+ this.indented = indented;
+ this.column = column;
+ this.type = type;
+ this.prev = prev;
+ this.info = info;
+ if (align != null) this.align = align;
+ }
+
+ function inScope(state, varname) {
+ for (var v = state.localVars; v; v = v.next)
+ if (v.name == varname) return true;
+ for (var cx = state.context; cx; cx = cx.prev) {
+ for (var v = cx.vars; v; v = v.next)
+ if (v.name == varname) return true;
+ }
+ }
+
+ function parseJS(state, style, type, content, stream) {
+ var cc = state.cc;
+ // Communicate our context to the combinators.
+ // (Less wasteful than consing up a hundred closures on every call.)
+ cx.state = state; cx.stream = stream; cx.marked = null, cx.cc = cc; cx.style = style;
+
+ if (!state.lexical.hasOwnProperty("align"))
+ state.lexical.align = true;
+
+ while(true) {
+ var combinator = cc.length ? cc.pop() : jsonMode ? expression : statement;
+ if (combinator(type, content)) {
+ while(cc.length && cc[cc.length - 1].lex)
+ cc.pop()();
+ if (cx.marked) return cx.marked;
+ if (type == "variable" && inScope(state, content)) return "variable-2";
+ return style;
+ }
+ }
+ }
+
+ // Combinator utils
+
+ var cx = {state: null, column: null, marked: null, cc: null};
+ function pass() {
+ for (var i = arguments.length - 1; i >= 0; i--) cx.cc.push(arguments[i]);
+ }
+ function cont() {
+ pass.apply(null, arguments);
+ return true;
+ }
+ function inList(name, list) {
+ for (var v = list; v; v = v.next) if (v.name == name) return true
+ return false;
+ }
+ function register(varname) {
+ var state = cx.state;
+ cx.marked = "def";
+ if (state.context) {
+ if (state.lexical.info == "var" && state.context && state.context.block) {
+ // FIXME function decls are also not block scoped
+ var newContext = registerVarScoped(varname, state.context)
+ if (newContext != null) {
+ state.context = newContext
+ return
+ }
+ } else if (!inList(varname, state.localVars)) {
+ state.localVars = new Var(varname, state.localVars)
+ return
+ }
+ }
+ // Fall through means this is global
+ if (parserConfig.globalVars && !inList(varname, state.globalVars))
+ state.globalVars = new Var(varname, state.globalVars)
+ }
+ function registerVarScoped(varname, context) {
+ if (!context) {
+ return null
+ } else if (context.block) {
+ var inner = registerVarScoped(varname, context.prev)
+ if (!inner) return null
+ if (inner == context.prev) return context
+ return new Context(inner, context.vars, true)
+ } else if (inList(varname, context.vars)) {
+ return context
+ } else {
+ return new Context(context.prev, new Var(varname, context.vars), false)
+ }
+ }
+
+ function isModifier(name) {
+ return name == "public" || name == "private" || name == "protected" || name == "abstract" || name == "readonly"
+ }
+
+ // Combinators
+
+ function Context(prev, vars, block) { this.prev = prev; this.vars = vars; this.block = block }
+ function Var(name, next) { this.name = name; this.next = next }
+
+ var defaultVars = new Var("this", new Var("arguments", null))
+ function pushcontext() {
+ cx.state.context = new Context(cx.state.context, cx.state.localVars, false)
+ cx.state.localVars = defaultVars
+ }
+ function pushblockcontext() {
+ cx.state.context = new Context(cx.state.context, cx.state.localVars, true)
+ cx.state.localVars = null
+ }
+ function popcontext() {
+ cx.state.localVars = cx.state.context.vars
+ cx.state.context = cx.state.context.prev
+ }
+ popcontext.lex = true
+ function pushlex(type, info) {
+ var result = function() {
+ var state = cx.state, indent = state.indented;
+ if (state.lexical.type == "stat") indent = state.lexical.indented;
+ else for (var outer = state.lexical; outer && outer.type == ")" && outer.align; outer = outer.prev)
+ indent = outer.indented;
+ state.lexical = new JSLexical(indent, cx.stream.column(), type, null, state.lexical, info);
+ };
+ result.lex = true;
+ return result;
+ }
+ function poplex() {
+ var state = cx.state;
+ if (state.lexical.prev) {
+ if (state.lexical.type == ")")
+ state.indented = state.lexical.indented;
+ state.lexical = state.lexical.prev;
+ }
+ }
+ poplex.lex = true;
+
+ function expect(wanted) {
+ function exp(type) {
+ if (type == wanted) return cont();
+ else if (wanted == ";" || type == "}" || type == ")" || type == "]") return pass();
+ else return cont(exp);
+ };
+ return exp;
+ }
+
+ function statement(type, value) {
+ if (type == "var") return cont(pushlex("vardef", value), vardef, expect(";"), poplex);
+ if (type == "keyword a") return cont(pushlex("form"), parenExpr, statement, poplex);
+ if (type == "keyword b") return cont(pushlex("form"), statement, poplex);
+ if (type == "keyword d") return cx.stream.match(/^\s*$/, false) ? cont() : cont(pushlex("stat"), maybeexpression, expect(";"), poplex);
+ if (type == "debugger") return cont(expect(";"));
+ if (type == "{") return cont(pushlex("}"), pushblockcontext, block, poplex, popcontext);
+ if (type == ";") return cont();
+ if (type == "if") {
+ if (cx.state.lexical.info == "else" && cx.state.cc[cx.state.cc.length - 1] == poplex)
+ cx.state.cc.pop()();
+ return cont(pushlex("form"), parenExpr, statement, poplex, maybeelse);
+ }
+ if (type == "function") return cont(functiondef);
+ if (type == "for") return cont(pushlex("form"), forspec, statement, poplex);
+ if (type == "class" || (isTS && value == "interface")) {
+ cx.marked = "keyword"
+ return cont(pushlex("form", type == "class" ? type : value), className, poplex)
+ }
+ if (type == "variable") {
+ if (isTS && value == "declare") {
+ cx.marked = "keyword"
+ return cont(statement)
+ } else if (isTS && (value == "module" || value == "enum" || value == "type") && cx.stream.match(/^\s*\w/, false)) {
+ cx.marked = "keyword"
+ if (value == "enum") return cont(enumdef);
+ else if (value == "type") return cont(typename, expect("operator"), typeexpr, expect(";"));
+ else return cont(pushlex("form"), pattern, expect("{"), pushlex("}"), block, poplex, poplex)
+ } else if (isTS && value == "namespace") {
+ cx.marked = "keyword"
+ return cont(pushlex("form"), expression, statement, poplex)
+ } else if (isTS && value == "abstract") {
+ cx.marked = "keyword"
+ return cont(statement)
+ } else {
+ return cont(pushlex("stat"), maybelabel);
+ }
+ }
+ if (type == "switch") return cont(pushlex("form"), parenExpr, expect("{"), pushlex("}", "switch"), pushblockcontext,
+ block, poplex, poplex, popcontext);
+ if (type == "case") return cont(expression, expect(":"));
+ if (type == "default") return cont(expect(":"));
+ if (type == "catch") return cont(pushlex("form"), pushcontext, maybeCatchBinding, statement, poplex, popcontext);
+ if (type == "export") return cont(pushlex("stat"), afterExport, poplex);
+ if (type == "import") return cont(pushlex("stat"), afterImport, poplex);
+ if (type == "async") return cont(statement)
+ if (value == "@") return cont(expression, statement)
+ return pass(pushlex("stat"), expression, expect(";"), poplex);
+ }
+ function maybeCatchBinding(type) {
+ if (type == "(") return cont(funarg, expect(")"))
+ }
+ function expression(type, value) {
+ return expressionInner(type, value, false);
+ }
+ function expressionNoComma(type, value) {
+ return expressionInner(type, value, true);
+ }
+ function parenExpr(type) {
+ if (type != "(") return pass()
+ return cont(pushlex(")"), maybeexpression, expect(")"), poplex)
+ }
+ function expressionInner(type, value, noComma) {
+ if (cx.state.fatArrowAt == cx.stream.start) {
+ var body = noComma ? arrowBodyNoComma : arrowBody;
+ if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, expect("=>"), body, popcontext);
+ else if (type == "variable") return pass(pushcontext, pattern, expect("=>"), body, popcontext);
+ }
+
+ var maybeop = noComma ? maybeoperatorNoComma : maybeoperatorComma;
+ if (atomicTypes.hasOwnProperty(type)) return cont(maybeop);
+ if (type == "function") return cont(functiondef, maybeop);
+ if (type == "class" || (isTS && value == "interface")) { cx.marked = "keyword"; return cont(pushlex("form"), classExpression, poplex); }
+ if (type == "keyword c" || type == "async") return cont(noComma ? expressionNoComma : expression);
+ if (type == "(") return cont(pushlex(")"), maybeexpression, expect(")"), poplex, maybeop);
+ if (type == "operator" || type == "spread") return cont(noComma ? expressionNoComma : expression);
+ if (type == "[") return cont(pushlex("]"), arrayLiteral, poplex, maybeop);
+ if (type == "{") return contCommasep(objprop, "}", null, maybeop);
+ if (type == "quasi") return pass(quasi, maybeop);
+ if (type == "new") return cont(maybeTarget(noComma));
+ if (type == "import") return cont(expression);
+ return cont();
+ }
+ function maybeexpression(type) {
+ if (type.match(/[;\}\)\],]/)) return pass();
+ return pass(expression);
+ }
+
+ function maybeoperatorComma(type, value) {
+ if (type == ",") return cont(maybeexpression);
+ return maybeoperatorNoComma(type, value, false);
+ }
+ function maybeoperatorNoComma(type, value, noComma) {
+ var me = noComma == false ? maybeoperatorComma : maybeoperatorNoComma;
+ var expr = noComma == false ? expression : expressionNoComma;
+ if (type == "=>") return cont(pushcontext, noComma ? arrowBodyNoComma : arrowBody, popcontext);
+ if (type == "operator") {
+ if (/\+\+|--/.test(value) || isTS && value == "!") return cont(me);
+ if (isTS && value == "<" && cx.stream.match(/^([^<>]|<[^<>]*>)*>\s*\(/, false))
+ return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, me);
+ if (value == "?") return cont(expression, expect(":"), expr);
+ return cont(expr);
+ }
+ if (type == "quasi") { return pass(quasi, me); }
+ if (type == ";") return;
+ if (type == "(") return contCommasep(expressionNoComma, ")", "call", me);
+ if (type == ".") return cont(property, me);
+ if (type == "[") return cont(pushlex("]"), maybeexpression, expect("]"), poplex, me);
+ if (isTS && value == "as") { cx.marked = "keyword"; return cont(typeexpr, me) }
+ if (type == "regexp") {
+ cx.state.lastType = cx.marked = "operator"
+ cx.stream.backUp(cx.stream.pos - cx.stream.start - 1)
+ return cont(expr)
+ }
+ }
+ function quasi(type, value) {
+ if (type != "quasi") return pass();
+ if (value.slice(value.length - 2) != "${") return cont(quasi);
+ return cont(expression, continueQuasi);
+ }
+ function continueQuasi(type) {
+ if (type == "}") {
+ cx.marked = "string-2";
+ cx.state.tokenize = tokenQuasi;
+ return cont(quasi);
+ }
+ }
+ function arrowBody(type) {
+ findFatArrow(cx.stream, cx.state);
+ return pass(type == "{" ? statement : expression);
+ }
+ function arrowBodyNoComma(type) {
+ findFatArrow(cx.stream, cx.state);
+ return pass(type == "{" ? statement : expressionNoComma);
+ }
+ function maybeTarget(noComma) {
+ return function(type) {
+ if (type == ".") return cont(noComma ? targetNoComma : target);
+ else if (type == "variable" && isTS) return cont(maybeTypeArgs, noComma ? maybeoperatorNoComma : maybeoperatorComma)
+ else return pass(noComma ? expressionNoComma : expression);
+ };
+ }
+ function target(_, value) {
+ if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorComma); }
+ }
+ function targetNoComma(_, value) {
+ if (value == "target") { cx.marked = "keyword"; return cont(maybeoperatorNoComma); }
+ }
+ function maybelabel(type) {
+ if (type == ":") return cont(poplex, statement);
+ return pass(maybeoperatorComma, expect(";"), poplex);
+ }
+ function property(type) {
+ if (type == "variable") {cx.marked = "property"; return cont();}
+ }
+ function objprop(type, value) {
+ if (type == "async") {
+ cx.marked = "property";
+ return cont(objprop);
+ } else if (type == "variable" || cx.style == "keyword") {
+ cx.marked = "property";
+ if (value == "get" || value == "set") return cont(getterSetter);
+ var m // Work around fat-arrow-detection complication for detecting typescript typed arrow params
+ if (isTS && cx.state.fatArrowAt == cx.stream.start && (m = cx.stream.match(/^\s*:\s*/, false)))
+ cx.state.fatArrowAt = cx.stream.pos + m[0].length
+ return cont(afterprop);
+ } else if (type == "number" || type == "string") {
+ cx.marked = jsonldMode ? "property" : (cx.style + " property");
+ return cont(afterprop);
+ } else if (type == "jsonld-keyword") {
+ return cont(afterprop);
+ } else if (isTS && isModifier(value)) {
+ cx.marked = "keyword"
+ return cont(objprop)
+ } else if (type == "[") {
+ return cont(expression, maybetype, expect("]"), afterprop);
+ } else if (type == "spread") {
+ return cont(expressionNoComma, afterprop);
+ } else if (value == "*") {
+ cx.marked = "keyword";
+ return cont(objprop);
+ } else if (type == ":") {
+ return pass(afterprop)
+ }
+ }
+ function getterSetter(type) {
+ if (type != "variable") return pass(afterprop);
+ cx.marked = "property";
+ return cont(functiondef);
+ }
+ function afterprop(type) {
+ if (type == ":") return cont(expressionNoComma);
+ if (type == "(") return pass(functiondef);
+ }
+ function commasep(what, end, sep) {
+ function proceed(type, value) {
+ if (sep ? sep.indexOf(type) > -1 : type == ",") {
+ var lex = cx.state.lexical;
+ if (lex.info == "call") lex.pos = (lex.pos || 0) + 1;
+ return cont(function(type, value) {
+ if (type == end || value == end) return pass()
+ return pass(what)
+ }, proceed);
+ }
+ if (type == end || value == end) return cont();
+ if (sep && sep.indexOf(";") > -1) return pass(what)
+ return cont(expect(end));
+ }
+ return function(type, value) {
+ if (type == end || value == end) return cont();
+ return pass(what, proceed);
+ };
+ }
+ function contCommasep(what, end, info) {
+ for (var i = 3; i < arguments.length; i++)
+ cx.cc.push(arguments[i]);
+ return cont(pushlex(end, info), commasep(what, end), poplex);
+ }
+ function block(type) {
+ if (type == "}") return cont();
+ return pass(statement, block);
+ }
+ function maybetype(type, value) {
+ if (isTS) {
+ if (type == ":") return cont(typeexpr);
+ if (value == "?") return cont(maybetype);
+ }
+ }
+ function maybetypeOrIn(type, value) {
+ if (isTS && (type == ":" || value == "in")) return cont(typeexpr)
+ }
+ function mayberettype(type) {
+ if (isTS && type == ":") {
+ if (cx.stream.match(/^\s*\w+\s+is\b/, false)) return cont(expression, isKW, typeexpr)
+ else return cont(typeexpr)
+ }
+ }
+ function isKW(_, value) {
+ if (value == "is") {
+ cx.marked = "keyword"
+ return cont()
+ }
+ }
+ function typeexpr(type, value) {
+ if (value == "keyof" || value == "typeof" || value == "infer") {
+ cx.marked = "keyword"
+ return cont(value == "typeof" ? expressionNoComma : typeexpr)
+ }
+ if (type == "variable" || value == "void") {
+ cx.marked = "type"
+ return cont(afterType)
+ }
+ if (value == "|" || value == "&") return cont(typeexpr)
+ if (type == "string" || type == "number" || type == "atom") return cont(afterType);
+ if (type == "[") return cont(pushlex("]"), commasep(typeexpr, "]", ","), poplex, afterType)
+ if (type == "{") return cont(pushlex("}"), commasep(typeprop, "}", ",;"), poplex, afterType)
+ if (type == "(") return cont(commasep(typearg, ")"), maybeReturnType, afterType)
+ if (type == "<") return cont(commasep(typeexpr, ">"), typeexpr)
+ }
+ function maybeReturnType(type) {
+ if (type == "=>") return cont(typeexpr)
+ }
+ function typeprop(type, value) {
+ if (type == "variable" || cx.style == "keyword") {
+ cx.marked = "property"
+ return cont(typeprop)
+ } else if (value == "?" || type == "number" || type == "string") {
+ return cont(typeprop)
+ } else if (type == ":") {
+ return cont(typeexpr)
+ } else if (type == "[") {
+ return cont(expect("variable"), maybetypeOrIn, expect("]"), typeprop)
+ } else if (type == "(") {
+ return pass(functiondecl, typeprop)
+ }
+ }
+ function typearg(type, value) {
+ if (type == "variable" && cx.stream.match(/^\s*[?:]/, false) || value == "?") return cont(typearg)
+ if (type == ":") return cont(typeexpr)
+ if (type == "spread") return cont(typearg)
+ return pass(typeexpr)
+ }
+ function afterType(type, value) {
+ if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
+ if (value == "|" || type == "." || value == "&") return cont(typeexpr)
+ if (type == "[") return cont(typeexpr, expect("]"), afterType)
+ if (value == "extends" || value == "implements") { cx.marked = "keyword"; return cont(typeexpr) }
+ if (value == "?") return cont(typeexpr, expect(":"), typeexpr)
+ }
+ function maybeTypeArgs(_, value) {
+ if (value == "<") return cont(pushlex(">"), commasep(typeexpr, ">"), poplex, afterType)
+ }
+ function typeparam() {
+ return pass(typeexpr, maybeTypeDefault)
+ }
+ function maybeTypeDefault(_, value) {
+ if (value == "=") return cont(typeexpr)
+ }
+ function vardef(_, value) {
+ if (value == "enum") {cx.marked = "keyword"; return cont(enumdef)}
+ return pass(pattern, maybetype, maybeAssign, vardefCont);
+ }
+ function pattern(type, value) {
+ if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(pattern) }
+ if (type == "variable") { register(value); return cont(); }
+ if (type == "spread") return cont(pattern);
+ if (type == "[") return contCommasep(eltpattern, "]");
+ if (type == "{") return contCommasep(proppattern, "}");
+ }
+ function proppattern(type, value) {
+ if (type == "variable" && !cx.stream.match(/^\s*:/, false)) {
+ register(value);
+ return cont(maybeAssign);
+ }
+ if (type == "variable") cx.marked = "property";
+ if (type == "spread") return cont(pattern);
+ if (type == "}") return pass();
+ if (type == "[") return cont(expression, expect(']'), expect(':'), proppattern);
+ return cont(expect(":"), pattern, maybeAssign);
+ }
+ function eltpattern() {
+ return pass(pattern, maybeAssign)
+ }
+ function maybeAssign(_type, value) {
+ if (value == "=") return cont(expressionNoComma);
+ }
+ function vardefCont(type) {
+ if (type == ",") return cont(vardef);
+ }
+ function maybeelse(type, value) {
+ if (type == "keyword b" && value == "else") return cont(pushlex("form", "else"), statement, poplex);
+ }
+ function forspec(type, value) {
+ if (value == "await") return cont(forspec);
+ if (type == "(") return cont(pushlex(")"), forspec1, poplex);
+ }
+ function forspec1(type) {
+ if (type == "var") return cont(vardef, forspec2);
+ if (type == "variable") return cont(forspec2);
+ return pass(forspec2)
+ }
+ function forspec2(type, value) {
+ if (type == ")") return cont()
+ if (type == ";") return cont(forspec2)
+ if (value == "in" || value == "of") { cx.marked = "keyword"; return cont(expression, forspec2) }
+ return pass(expression, forspec2)
+ }
+ function functiondef(type, value) {
+ if (value == "*") {cx.marked = "keyword"; return cont(functiondef);}
+ if (type == "variable") {register(value); return cont(functiondef);}
+ if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, statement, popcontext);
+ if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondef)
+ }
+ function functiondecl(type, value) {
+ if (value == "*") {cx.marked = "keyword"; return cont(functiondecl);}
+ if (type == "variable") {register(value); return cont(functiondecl);}
+ if (type == "(") return cont(pushcontext, pushlex(")"), commasep(funarg, ")"), poplex, mayberettype, popcontext);
+ if (isTS && value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, functiondecl)
+ }
+ function typename(type, value) {
+ if (type == "keyword" || type == "variable") {
+ cx.marked = "type"
+ return cont(typename)
+ } else if (value == "<") {
+ return cont(pushlex(">"), commasep(typeparam, ">"), poplex)
+ }
+ }
+ function funarg(type, value) {
+ if (value == "@") cont(expression, funarg)
+ if (type == "spread") return cont(funarg);
+ if (isTS && isModifier(value)) { cx.marked = "keyword"; return cont(funarg); }
+ if (isTS && type == "this") return cont(maybetype, maybeAssign)
+ return pass(pattern, maybetype, maybeAssign);
+ }
+ function classExpression(type, value) {
+ // Class expressions may have an optional name.
+ if (type == "variable") return className(type, value);
+ return classNameAfter(type, value);
+ }
+ function className(type, value) {
+ if (type == "variable") {register(value); return cont(classNameAfter);}
+ }
+ function classNameAfter(type, value) {
+ if (value == "<") return cont(pushlex(">"), commasep(typeparam, ">"), poplex, classNameAfter)
+ if (value == "extends" || value == "implements" || (isTS && type == ",")) {
+ if (value == "implements") cx.marked = "keyword";
+ return cont(isTS ? typeexpr : expression, classNameAfter);
+ }
+ if (type == "{") return cont(pushlex("}"), classBody, poplex);
+ }
+ function classBody(type, value) {
+ if (type == "async" ||
+ (type == "variable" &&
+ (value == "static" || value == "get" || value == "set" || (isTS && isModifier(value))) &&
+ cx.stream.match(/^\s+[\w$\xa1-\uffff]/, false))) {
+ cx.marked = "keyword";
+ return cont(classBody);
+ }
+ if (type == "variable" || cx.style == "keyword") {
+ cx.marked = "property";
+ return cont(classfield, classBody);
+ }
+ if (type == "number" || type == "string") return cont(classfield, classBody);
+ if (type == "[")
+ return cont(expression, maybetype, expect("]"), classfield, classBody)
+ if (value == "*") {
+ cx.marked = "keyword";
+ return cont(classBody);
+ }
+ if (isTS && type == "(") return pass(functiondecl, classBody)
+ if (type == ";" || type == ",") return cont(classBody);
+ if (type == "}") return cont();
+ if (value == "@") return cont(expression, classBody)
+ }
+ function classfield(type, value) {
+ if (value == "?") return cont(classfield)
+ if (type == ":") return cont(typeexpr, maybeAssign)
+ if (value == "=") return cont(expressionNoComma)
+ var context = cx.state.lexical.prev, isInterface = context && context.info == "interface"
+ return pass(isInterface ? functiondecl : functiondef)
+ }
+ function afterExport(type, value) {
+ if (value == "*") { cx.marked = "keyword"; return cont(maybeFrom, expect(";")); }
+ if (value == "default") { cx.marked = "keyword"; return cont(expression, expect(";")); }
+ if (type == "{") return cont(commasep(exportField, "}"), maybeFrom, expect(";"));
+ return pass(statement);
+ }
+ function exportField(type, value) {
+ if (value == "as") { cx.marked = "keyword"; return cont(expect("variable")); }
+ if (type == "variable") return pass(expressionNoComma, exportField);
+ }
+ function afterImport(type) {
+ if (type == "string") return cont();
+ if (type == "(") return pass(expression);
+ return pass(importSpec, maybeMoreImports, maybeFrom);
+ }
+ function importSpec(type, value) {
+ if (type == "{") return contCommasep(importSpec, "}");
+ if (type == "variable") register(value);
+ if (value == "*") cx.marked = "keyword";
+ return cont(maybeAs);
+ }
+ function maybeMoreImports(type) {
+ if (type == ",") return cont(importSpec, maybeMoreImports)
+ }
+ function maybeAs(_type, value) {
+ if (value == "as") { cx.marked = "keyword"; return cont(importSpec); }
+ }
+ function maybeFrom(_type, value) {
+ if (value == "from") { cx.marked = "keyword"; return cont(expression); }
+ }
+ function arrayLiteral(type) {
+ if (type == "]") return cont();
+ return pass(commasep(expressionNoComma, "]"));
+ }
+ function enumdef() {
+ return pass(pushlex("form"), pattern, expect("{"), pushlex("}"), commasep(enummember, "}"), poplex, poplex)
+ }
+ function enummember() {
+ return pass(pattern, maybeAssign);
+ }
+
+ function isContinuedStatement(state, textAfter) {
+ return state.lastType == "operator" || state.lastType == "," ||
+ isOperatorChar.test(textAfter.charAt(0)) ||
+ /[,.]/.test(textAfter.charAt(0));
+ }
+
+ function expressionAllowed(stream, state, backUp) {
+ return state.tokenize == tokenBase &&
+ /^(?:operator|sof|keyword [bcd]|case|new|export|default|spread|[\[{}\(,;:]|=>)$/.test(state.lastType) ||
+ (state.lastType == "quasi" && /\{\s*$/.test(stream.string.slice(0, stream.pos - (backUp || 0))))
+ }
+
+ // Interface
+
+ return {
+ startState: function(basecolumn) {
+ var state = {
+ tokenize: tokenBase,
+ lastType: "sof",
+ cc: [],
+ lexical: new JSLexical((basecolumn || 0) - indentUnit, 0, "block", false),
+ localVars: parserConfig.localVars,
+ context: parserConfig.localVars && new Context(null, null, false),
+ indented: basecolumn || 0
+ };
+ if (parserConfig.globalVars && typeof parserConfig.globalVars == "object")
+ state.globalVars = parserConfig.globalVars;
+ return state;
+ },
+
+ token: function(stream, state) {
+ if (stream.sol()) {
+ if (!state.lexical.hasOwnProperty("align"))
+ state.lexical.align = false;
+ state.indented = stream.indentation();
+ findFatArrow(stream, state);
+ }
+ if (state.tokenize != tokenComment && stream.eatSpace()) return null;
+ var style = state.tokenize(stream, state);
+ if (type == "comment") return style;
+ state.lastType = type == "operator" && (content == "++" || content == "--") ? "incdec" : type;
+ return parseJS(state, style, type, content, stream);
+ },
+
+ indent: function(state, textAfter) {
+ if (state.tokenize == tokenComment || state.tokenize == tokenQuasi) return CodeMirror.Pass;
+ if (state.tokenize != tokenBase) return 0;
+ var firstChar = textAfter && textAfter.charAt(0), lexical = state.lexical, top
+ // Kludge to prevent 'maybelse' from blocking lexical scope pops
+ if (!/^\s*else\b/.test(textAfter)) for (var i = state.cc.length - 1; i >= 0; --i) {
+ var c = state.cc[i];
+ if (c == poplex) lexical = lexical.prev;
+ else if (c != maybeelse) break;
+ }
+ while ((lexical.type == "stat" || lexical.type == "form") &&
+ (firstChar == "}" || ((top = state.cc[state.cc.length - 1]) &&
+ (top == maybeoperatorComma || top == maybeoperatorNoComma) &&
+ !/^[,\.=+\-*:?[\(]/.test(textAfter))))
+ lexical = lexical.prev;
+ if (statementIndent && lexical.type == ")" && lexical.prev.type == "stat")
+ lexical = lexical.prev;
+ var type = lexical.type, closing = firstChar == type;
+
+ if (type == "vardef") return lexical.indented + (state.lastType == "operator" || state.lastType == "," ? lexical.info.length + 1 : 0);
+ else if (type == "form" && firstChar == "{") return lexical.indented;
+ else if (type == "form") return lexical.indented + indentUnit;
+ else if (type == "stat")
+ return lexical.indented + (isContinuedStatement(state, textAfter) ? statementIndent || indentUnit : 0);
+ else if (lexical.info == "switch" && !closing && parserConfig.doubleIndentSwitch != false)
+ return lexical.indented + (/^(?:case|default)\b/.test(textAfter) ? indentUnit : 2 * indentUnit);
+ else if (lexical.align) return lexical.column + (closing ? 0 : 1);
+ else return lexical.indented + (closing ? 0 : indentUnit);
+ },
+
+ electricInput: /^\s*(?:case .*?:|default:|\{|\})$/,
+ blockCommentStart: jsonMode ? null : "/*",
+ blockCommentEnd: jsonMode ? null : "*/",
+ blockCommentContinue: jsonMode ? null : " * ",
+ lineComment: jsonMode ? null : "//",
+ fold: "brace",
+ closeBrackets: "()[]{}''\"\"``",
+
+ helperType: jsonMode ? "json" : "javascript",
+ jsonldMode: jsonldMode,
+ jsonMode: jsonMode,
+
+ expressionAllowed: expressionAllowed,
+
+ skipExpression: function(state) {
+ var top = state.cc[state.cc.length - 1]
+ if (top == expression || top == expressionNoComma) state.cc.pop()
+ }
+ };
+});
+
+CodeMirror.registerHelper("wordChars", "javascript", /[\w$]/);
+
+CodeMirror.defineMIME("text/javascript", "javascript");
+CodeMirror.defineMIME("text/ecmascript", "javascript");
+CodeMirror.defineMIME("application/javascript", "javascript");
+CodeMirror.defineMIME("application/x-javascript", "javascript");
+CodeMirror.defineMIME("application/ecmascript", "javascript");
+CodeMirror.defineMIME("application/json", {name: "javascript", json: true});
+CodeMirror.defineMIME("application/x-json", {name: "javascript", json: true});
+CodeMirror.defineMIME("application/ld+json", {name: "javascript", jsonld: true});
+CodeMirror.defineMIME("text/typescript", { name: "javascript", typescript: true });
+CodeMirror.defineMIME("application/typescript", { name: "javascript", typescript: true });
+
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/mode/jsx/jsx.js b/devtools/client/shared/sourceeditor/codemirror/mode/jsx/jsx.js
new file mode 100644
index 0000000000..3a69cbbf3b
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/mode/jsx/jsx.js
@@ -0,0 +1,148 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"), require("resource://devtools/client/shared/sourceeditor/codemirror/mode/xml/xml.js"), require("resource://devtools/client/shared/sourceeditor/codemirror/mode/javascript/javascript.js"))
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror", "../xml/xml", "../javascript/javascript"], mod)
+ else // Plain browser env
+ mod(CodeMirror)
+})(function(CodeMirror) {
+ "use strict"
+
+ // Depth means the amount of open braces in JS context, in XML
+ // context 0 means not in tag, 1 means in tag, and 2 means in tag
+ // and js block comment.
+ function Context(state, mode, depth, prev) {
+ this.state = state; this.mode = mode; this.depth = depth; this.prev = prev
+ }
+
+ function copyContext(context) {
+ return new Context(CodeMirror.copyState(context.mode, context.state),
+ context.mode,
+ context.depth,
+ context.prev && copyContext(context.prev))
+ }
+
+ CodeMirror.defineMode("jsx", function(config, modeConfig) {
+ var xmlMode = CodeMirror.getMode(config, {name: "xml", allowMissing: true, multilineTagIndentPastTag: false, allowMissingTagName: true})
+ var jsMode = CodeMirror.getMode(config, modeConfig && modeConfig.base || "javascript")
+
+ function flatXMLIndent(state) {
+ var tagName = state.tagName
+ state.tagName = null
+ var result = xmlMode.indent(state, "", "")
+ state.tagName = tagName
+ return result
+ }
+
+ function token(stream, state) {
+ if (state.context.mode == xmlMode)
+ return xmlToken(stream, state, state.context)
+ else
+ return jsToken(stream, state, state.context)
+ }
+
+ function xmlToken(stream, state, cx) {
+ if (cx.depth == 2) { // Inside a JS /* */ comment
+ if (stream.match(/^.*?\*\//)) cx.depth = 1
+ else stream.skipToEnd()
+ return "comment"
+ }
+
+ if (stream.peek() == "{") {
+ xmlMode.skipAttribute(cx.state)
+
+ var indent = flatXMLIndent(cx.state), xmlContext = cx.state.context
+ // If JS starts on same line as tag
+ if (xmlContext && stream.match(/^[^>]*>\s*$/, false)) {
+ while (xmlContext.prev && !xmlContext.startOfLine)
+ xmlContext = xmlContext.prev
+ // If tag starts the line, use XML indentation level
+ if (xmlContext.startOfLine) indent -= config.indentUnit
+ // Else use JS indentation level
+ else if (cx.prev.state.lexical) indent = cx.prev.state.lexical.indented
+ // Else if inside of tag
+ } else if (cx.depth == 1) {
+ indent += config.indentUnit
+ }
+
+ state.context = new Context(CodeMirror.startState(jsMode, indent),
+ jsMode, 0, state.context)
+ return null
+ }
+
+ if (cx.depth == 1) { // Inside of tag
+ if (stream.peek() == "<") { // Tag inside of tag
+ xmlMode.skipAttribute(cx.state)
+ state.context = new Context(CodeMirror.startState(xmlMode, flatXMLIndent(cx.state)),
+ xmlMode, 0, state.context)
+ return null
+ } else if (stream.match("//")) {
+ stream.skipToEnd()
+ return "comment"
+ } else if (stream.match("/*")) {
+ cx.depth = 2
+ return token(stream, state)
+ }
+ }
+
+ var style = xmlMode.token(stream, cx.state), cur = stream.current(), stop
+ if (/\btag\b/.test(style)) {
+ if (/>$/.test(cur)) {
+ if (cx.state.context) cx.depth = 0
+ else state.context = state.context.prev
+ } else if (/^</.test(cur)) {
+ cx.depth = 1
+ }
+ } else if (!style && (stop = cur.indexOf("{")) > -1) {
+ stream.backUp(cur.length - stop)
+ }
+ return style
+ }
+
+ function jsToken(stream, state, cx) {
+ if (stream.peek() == "<" && jsMode.expressionAllowed(stream, cx.state)) {
+ jsMode.skipExpression(cx.state)
+ state.context = new Context(CodeMirror.startState(xmlMode, jsMode.indent(cx.state, "", "")),
+ xmlMode, 0, state.context)
+ return null
+ }
+
+ var style = jsMode.token(stream, cx.state)
+ if (!style && cx.depth != null) {
+ var cur = stream.current()
+ if (cur == "{") {
+ cx.depth++
+ } else if (cur == "}") {
+ if (--cx.depth == 0) state.context = state.context.prev
+ }
+ }
+ return style
+ }
+
+ return {
+ startState: function() {
+ return {context: new Context(CodeMirror.startState(jsMode), jsMode)}
+ },
+
+ copyState: function(state) {
+ return {context: copyContext(state.context)}
+ },
+
+ token: token,
+
+ indent: function(state, textAfter, fullLine) {
+ return state.context.mode.indent(state.context.state, textAfter, fullLine)
+ },
+
+ innerMode: function(state) {
+ return state.context
+ }
+ }
+ }, "xml", "javascript")
+
+ CodeMirror.defineMIME("text/jsx", "jsx")
+ CodeMirror.defineMIME("text/typescript-jsx", {name: "jsx", base: {name: "javascript", typescript: true}})
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/mode/rust/rust.js b/devtools/client/shared/sourceeditor/codemirror/mode/rust/rust.js
new file mode 100644
index 0000000000..8139f5a1da
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/mode/rust/rust.js
@@ -0,0 +1,72 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"), require("resource://devtools/client/shared/sourceeditor/codemirror/mode/simple/simple.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror", "../../mode/simple/simple"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+"use strict";
+
+CodeMirror.defineSimpleMode("rust",{
+ start: [
+ // string and byte string
+ {regex: /b?"/, token: "string", next: "string"},
+ // raw string and raw byte string
+ {regex: /b?r"/, token: "string", next: "string_raw"},
+ {regex: /b?r#+"/, token: "string", next: "string_raw_hash"},
+ // character
+ {regex: /'(?:[^'\\]|\\(?:[nrt0'"]|x[\da-fA-F]{2}|u\{[\da-fA-F]{6}\}))'/, token: "string-2"},
+ // byte
+ {regex: /b'(?:[^']|\\(?:['\\nrt0]|x[\da-fA-F]{2}))'/, token: "string-2"},
+
+ {regex: /(?:(?:[0-9][0-9_]*)(?:(?:[Ee][+-]?[0-9_]+)|\.[0-9_]+(?:[Ee][+-]?[0-9_]+)?)(?:f32|f64)?)|(?:0(?:b[01_]+|(?:o[0-7_]+)|(?:x[0-9a-fA-F_]+))|(?:[0-9][0-9_]*))(?:u8|u16|u32|u64|i8|i16|i32|i64|isize|usize)?/,
+ token: "number"},
+ {regex: /(let(?:\s+mut)?|fn|enum|mod|struct|type)(\s+)([a-zA-Z_][a-zA-Z0-9_]*)/, token: ["keyword", null, "def"]},
+ {regex: /(?:abstract|alignof|as|box|break|continue|const|crate|do|else|enum|extern|fn|for|final|if|impl|in|loop|macro|match|mod|move|offsetof|override|priv|proc|pub|pure|ref|return|self|sizeof|static|struct|super|trait|type|typeof|unsafe|unsized|use|virtual|where|while|yield)\b/, token: "keyword"},
+ {regex: /\b(?:Self|isize|usize|char|bool|u8|u16|u32|u64|f16|f32|f64|i8|i16|i32|i64|str|Option)\b/, token: "atom"},
+ {regex: /\b(?:true|false|Some|None|Ok|Err)\b/, token: "builtin"},
+ {regex: /\b(fn)(\s+)([a-zA-Z_][a-zA-Z0-9_]*)/,
+ token: ["keyword", null ,"def"]},
+ {regex: /#!?\[.*\]/, token: "meta"},
+ {regex: /\/\/.*/, token: "comment"},
+ {regex: /\/\*/, token: "comment", next: "comment"},
+ {regex: /[-+\/*=<>!]+/, token: "operator"},
+ {regex: /[a-zA-Z_]\w*!/,token: "variable-3"},
+ {regex: /[a-zA-Z_]\w*/, token: "variable"},
+ {regex: /[\{\[\(]/, indent: true},
+ {regex: /[\}\]\)]/, dedent: true}
+ ],
+ string: [
+ {regex: /"/, token: "string", next: "start"},
+ {regex: /(?:[^\\"]|\\(?:.|$))*/, token: "string"}
+ ],
+ string_raw: [
+ {regex: /"/, token: "string", next: "start"},
+ {regex: /[^"]*/, token: "string"}
+ ],
+ string_raw_hash: [
+ {regex: /"#+/, token: "string", next: "start"},
+ {regex: /(?:[^"]|"(?!#))*/, token: "string"}
+ ],
+ comment: [
+ {regex: /.*?\*\//, token: "comment", next: "start"},
+ {regex: /.*/, token: "comment"}
+ ],
+ meta: {
+ dontIndentStates: ["comment"],
+ electricInput: /^\s*\}$/,
+ blockCommentStart: "/*",
+ blockCommentEnd: "*/",
+ lineComment: "//",
+ fold: "brace"
+ }
+});
+
+
+CodeMirror.defineMIME("text/x-rustsrc", "rust");
+CodeMirror.defineMIME("text/rust", "rust");
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/mode/simple/simple.js b/devtools/client/shared/sourceeditor/codemirror/mode/simple/simple.js
new file mode 100644
index 0000000000..bc2f7b5670
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/mode/simple/simple.js
@@ -0,0 +1,216 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+ "use strict";
+
+ CodeMirror.defineSimpleMode = function(name, states) {
+ CodeMirror.defineMode(name, function(config) {
+ return CodeMirror.simpleMode(config, states);
+ });
+ };
+
+ CodeMirror.simpleMode = function(config, states) {
+ ensureState(states, "start");
+ var states_ = {}, meta = states.meta || {}, hasIndentation = false;
+ for (var state in states) if (state != meta && states.hasOwnProperty(state)) {
+ var list = states_[state] = [], orig = states[state];
+ for (var i = 0; i < orig.length; i++) {
+ var data = orig[i];
+ list.push(new Rule(data, states));
+ if (data.indent || data.dedent) hasIndentation = true;
+ }
+ }
+ var mode = {
+ startState: function() {
+ return {state: "start", pending: null,
+ local: null, localState: null,
+ indent: hasIndentation ? [] : null};
+ },
+ copyState: function(state) {
+ var s = {state: state.state, pending: state.pending,
+ local: state.local, localState: null,
+ indent: state.indent && state.indent.slice(0)};
+ if (state.localState)
+ s.localState = CodeMirror.copyState(state.local.mode, state.localState);
+ if (state.stack)
+ s.stack = state.stack.slice(0);
+ for (var pers = state.persistentStates; pers; pers = pers.next)
+ s.persistentStates = {mode: pers.mode,
+ spec: pers.spec,
+ state: pers.state == state.localState ? s.localState : CodeMirror.copyState(pers.mode, pers.state),
+ next: s.persistentStates};
+ return s;
+ },
+ token: tokenFunction(states_, config),
+ innerMode: function(state) { return state.local && {mode: state.local.mode, state: state.localState}; },
+ indent: indentFunction(states_, meta)
+ };
+ if (meta) for (var prop in meta) if (meta.hasOwnProperty(prop))
+ mode[prop] = meta[prop];
+ return mode;
+ };
+
+ function ensureState(states, name) {
+ if (!states.hasOwnProperty(name))
+ throw new Error("Undefined state " + name + " in simple mode");
+ }
+
+ function toRegex(val, caret) {
+ if (!val) return /(?:)/;
+ var flags = "";
+ if (val instanceof RegExp) {
+ if (val.ignoreCase) flags = "i";
+ val = val.source;
+ } else {
+ val = String(val);
+ }
+ return new RegExp((caret === false ? "" : "^") + "(?:" + val + ")", flags);
+ }
+
+ function asToken(val) {
+ if (!val) return null;
+ if (val.apply) return val
+ if (typeof val == "string") return val.replace(/\./g, " ");
+ var result = [];
+ for (var i = 0; i < val.length; i++)
+ result.push(val[i] && val[i].replace(/\./g, " "));
+ return result;
+ }
+
+ function Rule(data, states) {
+ if (data.next || data.push) ensureState(states, data.next || data.push);
+ this.regex = toRegex(data.regex);
+ this.token = asToken(data.token);
+ this.data = data;
+ }
+
+ function tokenFunction(states, config) {
+ return function(stream, state) {
+ if (state.pending) {
+ var pend = state.pending.shift();
+ if (state.pending.length == 0) state.pending = null;
+ stream.pos += pend.text.length;
+ return pend.token;
+ }
+
+ if (state.local) {
+ if (state.local.end && stream.match(state.local.end)) {
+ var tok = state.local.endToken || null;
+ state.local = state.localState = null;
+ return tok;
+ } else {
+ var tok = state.local.mode.token(stream, state.localState), m;
+ if (state.local.endScan && (m = state.local.endScan.exec(stream.current())))
+ stream.pos = stream.start + m.index;
+ return tok;
+ }
+ }
+
+ var curState = states[state.state];
+ for (var i = 0; i < curState.length; i++) {
+ var rule = curState[i];
+ var matches = (!rule.data.sol || stream.sol()) && stream.match(rule.regex);
+ if (matches) {
+ if (rule.data.next) {
+ state.state = rule.data.next;
+ } else if (rule.data.push) {
+ (state.stack || (state.stack = [])).push(state.state);
+ state.state = rule.data.push;
+ } else if (rule.data.pop && state.stack && state.stack.length) {
+ state.state = state.stack.pop();
+ }
+
+ if (rule.data.mode)
+ enterLocalMode(config, state, rule.data.mode, rule.token);
+ if (rule.data.indent)
+ state.indent.push(stream.indentation() + config.indentUnit);
+ if (rule.data.dedent)
+ state.indent.pop();
+ var token = rule.token
+ if (token && token.apply) token = token(matches)
+ if (matches.length > 2 && rule.token && typeof rule.token != "string") {
+ state.pending = [];
+ for (var j = 2; j < matches.length; j++)
+ if (matches[j])
+ state.pending.push({text: matches[j], token: rule.token[j - 1]});
+ stream.backUp(matches[0].length - (matches[1] ? matches[1].length : 0));
+ return token[0];
+ } else if (token && token.join) {
+ return token[0];
+ } else {
+ return token;
+ }
+ }
+ }
+ stream.next();
+ return null;
+ };
+ }
+
+ function cmp(a, b) {
+ if (a === b) return true;
+ if (!a || typeof a != "object" || !b || typeof b != "object") return false;
+ var props = 0;
+ for (var prop in a) if (a.hasOwnProperty(prop)) {
+ if (!b.hasOwnProperty(prop) || !cmp(a[prop], b[prop])) return false;
+ props++;
+ }
+ for (var prop in b) if (b.hasOwnProperty(prop)) props--;
+ return props == 0;
+ }
+
+ function enterLocalMode(config, state, spec, token) {
+ var pers;
+ if (spec.persistent) for (var p = state.persistentStates; p && !pers; p = p.next)
+ if (spec.spec ? cmp(spec.spec, p.spec) : spec.mode == p.mode) pers = p;
+ var mode = pers ? pers.mode : spec.mode || CodeMirror.getMode(config, spec.spec);
+ var lState = pers ? pers.state : CodeMirror.startState(mode);
+ if (spec.persistent && !pers)
+ state.persistentStates = {mode: mode, spec: spec.spec, state: lState, next: state.persistentStates};
+
+ state.localState = lState;
+ state.local = {mode: mode,
+ end: spec.end && toRegex(spec.end),
+ endScan: spec.end && spec.forceEnd !== false && toRegex(spec.end, false),
+ endToken: token && token.join ? token[token.length - 1] : token};
+ }
+
+ function indexOf(val, arr) {
+ for (var i = 0; i < arr.length; i++) if (arr[i] === val) return true;
+ }
+
+ function indentFunction(states, meta) {
+ return function(state, textAfter, line) {
+ if (state.local && state.local.mode.indent)
+ return state.local.mode.indent(state.localState, textAfter, line);
+ if (state.indent == null || state.local || meta.dontIndentStates && indexOf(state.state, meta.dontIndentStates) > -1)
+ return CodeMirror.Pass;
+
+ var pos = state.indent.length - 1, rules = states[state.state];
+ scan: for (;;) {
+ for (var i = 0; i < rules.length; i++) {
+ var rule = rules[i];
+ if (rule.data.dedent && rule.data.dedentIfLineStart !== false) {
+ var m = rule.regex.exec(textAfter);
+ if (m && m[0]) {
+ pos--;
+ if (rule.next || rule.push) rules = states[rule.next || rule.push];
+ textAfter = textAfter.slice(m[0].length);
+ continue scan;
+ }
+ }
+ }
+ break;
+ }
+ return pos < 0 ? 0 : state.indent[pos];
+ };
+ }
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/mode/wasm/wasm.js b/devtools/client/shared/sourceeditor/codemirror/mode/wasm/wasm.js
new file mode 100644
index 0000000000..39122d4bd4
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/mode/wasm/wasm.js
@@ -0,0 +1,203 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+// WebAssembly experimental syntax highlight add-on for CodeMirror.
+
+(function (root, factory) {
+ if (typeof define === 'function' && define.amd) {
+ define(["../../lib/codemirror"], factory);
+ } else if (typeof exports !== 'undefined') {
+ factory(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ } else {
+ factory(root.CodeMirror);
+ }
+}(this, function (CodeMirror) {
+"use strict";
+
+var isWordChar = /[\w\$_\.\\\/@]/;
+
+function createLookupTable(list) {
+ var obj = Object.create(null);
+ list.forEach(function (key) {
+ obj[key] = true;
+ });
+ return obj;
+}
+
+CodeMirror.defineMode("wasm", function() {
+ var keywords = createLookupTable([
+ "function", "import", "export", "table", "memory", "segment", "as", "type",
+ "of", "from", "typeof", "br", "br_if", "loop", "br_table", "if", "else",
+ "call", "call_import", "call_indirect", "nop", "unreachable", "var",
+ "align", "select", "return"]);
+ var builtins = createLookupTable([
+ "i32:8", "i32:8u", "i32:8s", "i32:16", "i32:16u", "i32:16s",
+ "i64:8", "i64:8u", "i64:8s", "i64:16", "i64:16u", "i64:16s",
+ "i64:32", "i64:32u", "i64:32s",
+ "i32.add", "i32.sub", "i32.mul", "i32.div_s", "i32.div_u",
+ "i32.rem_s", "i32.rem_u", "i32.and", "i32.or", "i32.xor",
+ "i32.shl", "i32.shr_u", "i32.shr_s", "i32.rotr", "i32.rotl",
+ "i32.eq", "i32.ne", "i32.lt_s", "i32.le_s", "i32.lt_u",
+ "i32.le_u", "i32.gt_s", "i32.ge_s", "i32.gt_u", "i32.ge_u",
+ "i32.clz", "i32.ctz", "i32.popcnt", "i32.eqz", "i64.add",
+ "i64.sub", "i64.mul", "i64.div_s", "i64.div_u", "i64.rem_s",
+ "i64.rem_u", "i64.and", "i64.or", "i64.xor", "i64.shl",
+ "i64.shr_u", "i64.shr_s", "i64.rotr", "i64.rotl", "i64.eq",
+ "i64.ne", "i64.lt_s", "i64.le_s", "i64.lt_u", "i64.le_u",
+ "i64.gt_s", "i64.ge_s", "i64.gt_u", "i64.ge_u", "i64.clz",
+ "i64.ctz", "i64.popcnt", "i64.eqz", "f32.add", "f32.sub",
+ "f32.mul", "f32.div", "f32.min", "f32.max", "f32.abs",
+ "f32.neg", "f32.copysign", "f32.ceil", "f32.floor", "f32.trunc",
+ "f32.nearest", "f32.sqrt", "f32.eq", "f32.ne", "f32.lt",
+ "f32.le", "f32.gt", "f32.ge", "f64.add", "f64.sub", "f64.mul",
+ "f64.div", "f64.min", "f64.max", "f64.abs", "f64.neg",
+ "f64.copysign", "f64.ceil", "f64.floor", "f64.trunc", "f64.nearest",
+ "f64.sqrt", "f64.eq", "f64.ne", "f64.lt", "f64.le", "f64.gt",
+ "f64.ge", "i32.trunc_s/f32", "i32.trunc_s/f64", "i32.trunc_u/f32",
+ "i32.trunc_u/f64", "i32.wrap/i64", "i64.trunc_s/f32",
+ "i64.trunc_s/f64", "i64.trunc_u/f32", "i64.trunc_u/f64",
+ "i64.extend_s/i32", "i64.extend_u/i32", "f32.convert_s/i32",
+ "f32.convert_u/i32", "f32.convert_s/i64", "f32.convert_u/i64",
+ "f32.demote/f64", "f32.reinterpret/i32", "f64.convert_s/i32",
+ "f64.convert_u/i32", "f64.convert_s/i64", "f64.convert_u/i64",
+ "f64.promote/f32", "f64.reinterpret/i64", "i32.reinterpret/f32",
+ "i64.reinterpret/f64"]);
+ var dataTypes = createLookupTable(["i32", "i64", "f32", "f64"]);
+ var isUnaryOperator = /[\-!]/;
+ var operators = createLookupTable([
+ "+", "-", "*", "/", "/s", "/u", "%", "%s", "%u",
+ "<<", ">>u", ">>s", ">=", "<=", "==", "!=",
+ "<s", "<u", "<=s", "<=u", ">=s", ">=u", ">s", ">u",
+ "<", ">", "=", "&", "|", "^", "!"]);
+
+ function tokenBase(stream, state) {
+ var ch = stream.next();
+ if (ch === "$") {
+ stream.eatWhile(isWordChar);
+ return "variable";
+ }
+ if (ch === "@") {
+ stream.eatWhile(isWordChar);
+ return "meta";
+ }
+ if (ch === '"') {
+ state.tokenize = tokenString(ch);
+ return state.tokenize(stream, state);
+ }
+ if (ch == "/") {
+ if (stream.eat("*")) {
+ state.tokenize = tokenComment;
+ return tokenComment(stream, state);
+ } else if (stream.eat("/")) {
+ stream.skipToEnd();
+ return "comment";
+ }
+ }
+ if (/\d/.test(ch) ||
+ ((ch === "-" || ch === "+") && /\d/.test(stream.peek()))) {
+ stream.eatWhile(/[\w\._\-+]/);
+ return "number";
+ }
+ if (/[\[\]\(\)\{\},:]/.test(ch)) {
+ return null;
+ }
+ if (isUnaryOperator.test(ch)) {
+ return "operator";
+ }
+ stream.eatWhile(isWordChar);
+ var word = stream.current();
+
+ if (word in operators) {
+ return "operator";
+ }
+ if (word in keywords){
+ return "keyword";
+ }
+ if (word in dataTypes) {
+ if (!stream.eat(":")) {
+ return "builtin";
+ }
+ stream.eatWhile(isWordChar);
+ word = stream.current();
+ // fall thru for "builtin" check
+ }
+ if (word in builtins) {
+ return "builtin";
+ }
+
+ if (word === "Temporary") {
+ // Nightly has header with some text graphics -- skipping it.
+ state.tokenize = tokenTemporary;
+ return state.tokenize(stream, state);
+ }
+ return null;
+ }
+
+ function tokenComment(stream, state) {
+ state.commentDepth = 1;
+ var next;
+ while ((next = stream.next()) != null) {
+ if (next === "*" && stream.eat("/")) {
+ if (--state.commentDepth === 0) {
+ state.tokenize = null;
+ return "comment";
+ }
+ }
+ if (next === "/" && stream.eat("*")) {
+ // Nested comment
+ state.commentDepth++;
+ }
+ }
+ return "comment";
+ }
+
+ function tokenTemporary(stream, state) {
+ var next, endState = state.commentState;
+ // Skipping until "text support (Work In Progress):" is found.
+ while ((next = stream.next()) != null) {
+ if (endState === 0 && next === "t") {
+ endState = 1;
+ } else if (endState === 1 && next === ":") {
+ state.tokenize = null;
+ state.commentState = 0;
+ endState = 2;
+ return "comment";
+ }
+ }
+ state.commentState = endState;
+ return "comment";
+ }
+
+ function tokenString(quote) {
+ return function(stream, state) {
+ var escaped = false, next, end = false;
+ while ((next = stream.next()) != null) {
+ if (next == quote && !escaped) {
+ state.tokenize = null;
+ return "string";
+ }
+ escaped = !escaped && next === "\\";
+ }
+ return "string";
+ };
+ }
+
+ return {
+ startState: function() {
+ return {tokenize: null, commentState: 0, commentDepth: 0};
+ },
+
+ token: function(stream, state) {
+ if (stream.eatSpace()) return null;
+ var style = (state.tokenize || tokenBase)(stream, state);
+ return style;
+ }
+ };
+});
+
+CodeMirror.registerHelper("wordChars", "wasm", isWordChar);
+
+CodeMirror.defineMIME("text/wasm", "wasm");
+
+}));
diff --git a/devtools/client/shared/sourceeditor/codemirror/mode/xml/xml.js b/devtools/client/shared/sourceeditor/codemirror/mode/xml/xml.js
new file mode 100644
index 0000000000..5b3320297a
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/mode/xml/xml.js
@@ -0,0 +1,413 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function(mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/sourceeditor/codemirror/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function(CodeMirror) {
+"use strict";
+
+var htmlConfig = {
+ autoSelfClosers: {'area': true, 'base': true, 'br': true, 'col': true, 'command': true,
+ 'embed': true, 'frame': true, 'hr': true, 'img': true, 'input': true,
+ 'keygen': true, 'link': true, 'meta': true, 'param': true, 'source': true,
+ 'track': true, 'wbr': true, 'menuitem': true},
+ implicitlyClosed: {'dd': true, 'li': true, 'optgroup': true, 'option': true, 'p': true,
+ 'rp': true, 'rt': true, 'tbody': true, 'td': true, 'tfoot': true,
+ 'th': true, 'tr': true},
+ contextGrabbers: {
+ 'dd': {'dd': true, 'dt': true},
+ 'dt': {'dd': true, 'dt': true},
+ 'li': {'li': true},
+ 'option': {'option': true, 'optgroup': true},
+ 'optgroup': {'optgroup': true},
+ 'p': {'address': true, 'article': true, 'aside': true, 'blockquote': true, 'dir': true,
+ 'div': true, 'dl': true, 'fieldset': true, 'footer': true, 'form': true,
+ 'h1': true, 'h2': true, 'h3': true, 'h4': true, 'h5': true, 'h6': true,
+ 'header': true, 'hgroup': true, 'hr': true, 'menu': true, 'nav': true, 'ol': true,
+ 'p': true, 'pre': true, 'section': true, 'table': true, 'ul': true},
+ 'rp': {'rp': true, 'rt': true},
+ 'rt': {'rp': true, 'rt': true},
+ 'tbody': {'tbody': true, 'tfoot': true},
+ 'td': {'td': true, 'th': true},
+ 'tfoot': {'tbody': true},
+ 'th': {'td': true, 'th': true},
+ 'thead': {'tbody': true, 'tfoot': true},
+ 'tr': {'tr': true}
+ },
+ doNotIndent: {"pre": true},
+ allowUnquoted: true,
+ allowMissing: true,
+ caseFold: true
+}
+
+var xmlConfig = {
+ autoSelfClosers: {},
+ implicitlyClosed: {},
+ contextGrabbers: {},
+ doNotIndent: {},
+ allowUnquoted: false,
+ allowMissing: false,
+ allowMissingTagName: false,
+ caseFold: false
+}
+
+CodeMirror.defineMode("xml", function(editorConf, config_) {
+ var indentUnit = editorConf.indentUnit
+ var config = {}
+ var defaults = config_.htmlMode ? htmlConfig : xmlConfig
+ for (var prop in defaults) config[prop] = defaults[prop]
+ for (var prop in config_) config[prop] = config_[prop]
+
+ // Return variables for tokenizers
+ var type, setStyle;
+
+ function inText(stream, state) {
+ function chain(parser) {
+ state.tokenize = parser;
+ return parser(stream, state);
+ }
+
+ var ch = stream.next();
+ if (ch == "<") {
+ if (stream.eat("!")) {
+ if (stream.eat("[")) {
+ if (stream.match("CDATA[")) return chain(inBlock("atom", "]]>"));
+ else return null;
+ } else if (stream.match("--")) {
+ return chain(inBlock("comment", "-->"));
+ } else if (stream.match("DOCTYPE", true, true)) {
+ stream.eatWhile(/[\w\._\-]/);
+ return chain(doctype(1));
+ } else {
+ return null;
+ }
+ } else if (stream.eat("?")) {
+ stream.eatWhile(/[\w\._\-]/);
+ state.tokenize = inBlock("meta", "?>");
+ return "meta";
+ } else {
+ type = stream.eat("/") ? "closeTag" : "openTag";
+ state.tokenize = inTag;
+ return "tag bracket";
+ }
+ } else if (ch == "&") {
+ var ok;
+ if (stream.eat("#")) {
+ if (stream.eat("x")) {
+ ok = stream.eatWhile(/[a-fA-F\d]/) && stream.eat(";");
+ } else {
+ ok = stream.eatWhile(/[\d]/) && stream.eat(";");
+ }
+ } else {
+ ok = stream.eatWhile(/[\w\.\-:]/) && stream.eat(";");
+ }
+ return ok ? "atom" : "error";
+ } else {
+ stream.eatWhile(/[^&<]/);
+ return null;
+ }
+ }
+ inText.isInText = true;
+
+ function inTag(stream, state) {
+ var ch = stream.next();
+ if (ch == ">" || (ch == "/" && stream.eat(">"))) {
+ state.tokenize = inText;
+ type = ch == ">" ? "endTag" : "selfcloseTag";
+ return "tag bracket";
+ } else if (ch == "=") {
+ type = "equals";
+ return null;
+ } else if (ch == "<") {
+ state.tokenize = inText;
+ state.state = baseState;
+ state.tagName = state.tagStart = null;
+ var next = state.tokenize(stream, state);
+ return next ? next + " tag error" : "tag error";
+ } else if (/[\'\"]/.test(ch)) {
+ state.tokenize = inAttribute(ch);
+ state.stringStartCol = stream.column();
+ return state.tokenize(stream, state);
+ } else {
+ stream.match(/^[^\s\u00a0=<>\"\']*[^\s\u00a0=<>\"\'\/]/);
+ return "word";
+ }
+ }
+
+ function inAttribute(quote) {
+ var closure = function(stream, state) {
+ while (!stream.eol()) {
+ if (stream.next() == quote) {
+ state.tokenize = inTag;
+ break;
+ }
+ }
+ return "string";
+ };
+ closure.isInAttribute = true;
+ return closure;
+ }
+
+ function inBlock(style, terminator) {
+ return function(stream, state) {
+ while (!stream.eol()) {
+ if (stream.match(terminator)) {
+ state.tokenize = inText;
+ break;
+ }
+ stream.next();
+ }
+ return style;
+ }
+ }
+
+ function doctype(depth) {
+ return function(stream, state) {
+ var ch;
+ while ((ch = stream.next()) != null) {
+ if (ch == "<") {
+ state.tokenize = doctype(depth + 1);
+ return state.tokenize(stream, state);
+ } else if (ch == ">") {
+ if (depth == 1) {
+ state.tokenize = inText;
+ break;
+ } else {
+ state.tokenize = doctype(depth - 1);
+ return state.tokenize(stream, state);
+ }
+ }
+ }
+ return "meta";
+ };
+ }
+
+ function Context(state, tagName, startOfLine) {
+ this.prev = state.context;
+ this.tagName = tagName;
+ this.indent = state.indented;
+ this.startOfLine = startOfLine;
+ if (config.doNotIndent.hasOwnProperty(tagName) || (state.context && state.context.noIndent))
+ this.noIndent = true;
+ }
+ function popContext(state) {
+ if (state.context) state.context = state.context.prev;
+ }
+ function maybePopContext(state, nextTagName) {
+ var parentTagName;
+ while (true) {
+ if (!state.context) {
+ return;
+ }
+ parentTagName = state.context.tagName;
+ if (!config.contextGrabbers.hasOwnProperty(parentTagName) ||
+ !config.contextGrabbers[parentTagName].hasOwnProperty(nextTagName)) {
+ return;
+ }
+ popContext(state);
+ }
+ }
+
+ function baseState(type, stream, state) {
+ if (type == "openTag") {
+ state.tagStart = stream.column();
+ return tagNameState;
+ } else if (type == "closeTag") {
+ return closeTagNameState;
+ } else {
+ return baseState;
+ }
+ }
+ function tagNameState(type, stream, state) {
+ if (type == "word") {
+ state.tagName = stream.current();
+ setStyle = "tag";
+ return attrState;
+ } else if (config.allowMissingTagName && type == "endTag") {
+ setStyle = "tag bracket";
+ return attrState(type, stream, state);
+ } else {
+ setStyle = "error";
+ return tagNameState;
+ }
+ }
+ function closeTagNameState(type, stream, state) {
+ if (type == "word") {
+ var tagName = stream.current();
+ if (state.context && state.context.tagName != tagName &&
+ config.implicitlyClosed.hasOwnProperty(state.context.tagName))
+ popContext(state);
+ if ((state.context && state.context.tagName == tagName) || config.matchClosing === false) {
+ setStyle = "tag";
+ return closeState;
+ } else {
+ setStyle = "tag error";
+ return closeStateErr;
+ }
+ } else if (config.allowMissingTagName && type == "endTag") {
+ setStyle = "tag bracket";
+ return closeState(type, stream, state);
+ } else {
+ setStyle = "error";
+ return closeStateErr;
+ }
+ }
+
+ function closeState(type, _stream, state) {
+ if (type != "endTag") {
+ setStyle = "error";
+ return closeState;
+ }
+ popContext(state);
+ return baseState;
+ }
+ function closeStateErr(type, stream, state) {
+ setStyle = "error";
+ return closeState(type, stream, state);
+ }
+
+ function attrState(type, _stream, state) {
+ if (type == "word") {
+ setStyle = "attribute";
+ return attrEqState;
+ } else if (type == "endTag" || type == "selfcloseTag") {
+ var tagName = state.tagName, tagStart = state.tagStart;
+ state.tagName = state.tagStart = null;
+ if (type == "selfcloseTag" ||
+ config.autoSelfClosers.hasOwnProperty(tagName)) {
+ maybePopContext(state, tagName);
+ } else {
+ maybePopContext(state, tagName);
+ state.context = new Context(state, tagName, tagStart == state.indented);
+ }
+ return baseState;
+ }
+ setStyle = "error";
+ return attrState;
+ }
+ function attrEqState(type, stream, state) {
+ if (type == "equals") return attrValueState;
+ if (!config.allowMissing) setStyle = "error";
+ return attrState(type, stream, state);
+ }
+ function attrValueState(type, stream, state) {
+ if (type == "string") return attrContinuedState;
+ if (type == "word" && config.allowUnquoted) {setStyle = "string"; return attrState;}
+ setStyle = "error";
+ return attrState(type, stream, state);
+ }
+ function attrContinuedState(type, stream, state) {
+ if (type == "string") return attrContinuedState;
+ return attrState(type, stream, state);
+ }
+
+ return {
+ startState: function(baseIndent) {
+ var state = {tokenize: inText,
+ state: baseState,
+ indented: baseIndent || 0,
+ tagName: null, tagStart: null,
+ context: null}
+ if (baseIndent != null) state.baseIndent = baseIndent
+ return state
+ },
+
+ token: function(stream, state) {
+ if (!state.tagName && stream.sol())
+ state.indented = stream.indentation();
+
+ if (stream.eatSpace()) return null;
+ type = null;
+ var style = state.tokenize(stream, state);
+ if ((style || type) && style != "comment") {
+ setStyle = null;
+ state.state = state.state(type || style, stream, state);
+ if (setStyle)
+ style = setStyle == "error" ? style + " error" : setStyle;
+ }
+ return style;
+ },
+
+ indent: function(state, textAfter, fullLine) {
+ var context = state.context;
+ // Indent multi-line strings (e.g. css).
+ if (state.tokenize.isInAttribute) {
+ if (state.tagStart == state.indented)
+ return state.stringStartCol + 1;
+ else
+ return state.indented + indentUnit;
+ }
+ if (context && context.noIndent) return CodeMirror.Pass;
+ if (state.tokenize != inTag && state.tokenize != inText)
+ return fullLine ? fullLine.match(/^(\s*)/)[0].length : 0;
+ // Indent the starts of attribute names.
+ if (state.tagName) {
+ if (config.multilineTagIndentPastTag !== false)
+ return state.tagStart + state.tagName.length + 2;
+ else
+ return state.tagStart + indentUnit * (config.multilineTagIndentFactor || 1);
+ }
+ if (config.alignCDATA && /<!\[CDATA\[/.test(textAfter)) return 0;
+ var tagAfter = textAfter && /^<(\/)?([\w_:\.-]*)/.exec(textAfter);
+ if (tagAfter && tagAfter[1]) { // Closing tag spotted
+ while (context) {
+ if (context.tagName == tagAfter[2]) {
+ context = context.prev;
+ break;
+ } else if (config.implicitlyClosed.hasOwnProperty(context.tagName)) {
+ context = context.prev;
+ } else {
+ break;
+ }
+ }
+ } else if (tagAfter) { // Opening tag spotted
+ while (context) {
+ var grabbers = config.contextGrabbers[context.tagName];
+ if (grabbers && grabbers.hasOwnProperty(tagAfter[2]))
+ context = context.prev;
+ else
+ break;
+ }
+ }
+ while (context && context.prev && !context.startOfLine)
+ context = context.prev;
+ if (context) return context.indent + indentUnit;
+ else return state.baseIndent || 0;
+ },
+
+ electricInput: /<\/[\s\w:]+>$/,
+ blockCommentStart: "<!--",
+ blockCommentEnd: "-->",
+
+ configuration: config.htmlMode ? "html" : "xml",
+ helperType: config.htmlMode ? "html" : "xml",
+
+ skipAttribute: function(state) {
+ if (state.state == attrValueState)
+ state.state = attrState
+ },
+
+ xmlCurrentTag: function(state) {
+ return state.tagName ? {name: state.tagName, close: state.type == "closeTag"} : null
+ },
+
+ xmlCurrentContext: function(state) {
+ var context = []
+ for (var cx = state.context; cx; cx = cx.prev)
+ if (cx.tagName) context.push(cx.tagName)
+ return context.reverse()
+ }
+ };
+});
+
+CodeMirror.defineMIME("text/xml", "xml");
+CodeMirror.defineMIME("application/xml", "xml");
+if (!CodeMirror.mimeModes.hasOwnProperty("text/html"))
+ CodeMirror.defineMIME("text/html", {name: "xml", htmlMode: true});
+
+});
diff --git a/devtools/client/shared/sourceeditor/codemirror/mozilla.css b/devtools/client/shared/sourceeditor/codemirror/mozilla.css
new file mode 100644
index 0000000000..419f29cf68
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror/mozilla.css
@@ -0,0 +1,364 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+
+:root {
+ --breakpoint-active-color: rgba(44,187,15,.2);
+ --breakpoint-active-color-hover: rgba(44,187,15,.5);
+}
+
+.theme-dark:root {
+ --breakpoint-active-color: rgba(0,255,175,.4);
+ --breakpoint-active-color-hover: rgba(0,255,175,.7);
+}
+
+/* We don't want the focus style to be displayed on the CodeMirror scrollbars.
+ * See Bug 1590707.
+ */
+.CodeMirror-vscrollbar, .CodeMirror-hscrollbar {
+ outline: none !important;
+}
+
+.CodeMirror .errors {
+ width: 16px;
+}
+
+.CodeMirror .error {
+ display: inline-block;
+ margin-left: 5px;
+ width: 12px;
+ height: 12px;
+ background-repeat: no-repeat;
+ background-position: center;
+ background-size: contain;
+ opacity: 0.75;
+}
+
+.CodeMirror .hit-counts {
+ width: 6px;
+}
+
+.CodeMirror .hit-count {
+ display: inline-block;
+ height: 12px;
+ border: solid rgba(0,0,0,0.2);
+ border-width: 1px 1px 1px 0;
+ border-radius: 0 3px 3px 0;
+ padding: 0 3px;
+ font-size: 10px;
+ pointer-events: none;
+}
+
+.CodeMirror-linenumber:before {
+ content: " ";
+ display: block;
+ width: calc(100% - 3px);
+ position: absolute;
+ top: 1px;
+ left: 0;
+ height: 12px;
+ z-index: -1;
+ background-size: calc(100% - 2px) 12px;
+ background-repeat: no-repeat;
+ background-position: right center;
+ padding-inline-end: 9px;
+}
+
+.breakpoint .CodeMirror-linenumber {
+ color: var(--theme-body-background);
+}
+
+.debug-line .CodeMirror-linenumber {
+ background-color: var(--breakpoint-active-color);
+}
+
+.theme-dark .debug-line .CodeMirror-linenumber {
+ color: #c0c0c0;
+}
+
+.debug-line .CodeMirror-line {
+ background-color: var(--breakpoint-active-color) !important;
+}
+
+/* Don't display the highlight color since the debug line
+ is already highlighted */
+.debug-line .CodeMirror-activeline-background {
+ display: none;
+}
+
+.CodeMirror {
+ cursor: text;
+ height: 100%;
+}
+
+.CodeMirror-gutters {
+ cursor: default;
+}
+
+.cm-trailingspace {
+ background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAQAAAACCAYAAAB/qH1jAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH3QUXCToH00Y1UgAAACFJREFUCNdjPMDBUc/AwNDAAAFMTAwMDA0OP34wQgX/AQBYgwYEx4f9lQAAAABJRU5ErkJggg==");
+ opacity: 0.75;
+ background-position: left bottom;
+ background-repeat: repeat-x;
+}
+
+/* Search highlight style
+ * cm-searching is used in Style Editor, and cm-highlight in Debugger */
+.cm-searching,
+.cm-highlight {
+ border-bottom: 1px solid var(--theme-contrast-border);
+ /* Use the translucent yellow background, because we want the text selection
+ background (CodeMirror-selected) to show through this. */
+ background-color: var(--theme-contrast-background-alpha);
+}
+
+/* CodeMirror dialogs styling */
+
+.CodeMirror-dialog {
+ padding: 4px 3px;
+}
+
+.CodeMirror-dialog,
+.CodeMirror-dialog input {
+ font: message-box;
+}
+
+/* Fold addon */
+
+.CodeMirror-foldmarker {
+ display: inline-block;
+ font-family: sans-serif;
+ line-height: 10px;
+ margin: 0 1px;
+ padding: 0 2px;
+ border-radius: 3px;
+ border: solid 1px var(--theme-splitter-color);
+ color: var(--theme-body-color);
+ background-color: var(--theme-sidebar-background);
+ cursor: pointer;
+}
+
+.CodeMirror-foldgutter {
+ width: 16px; /* Same as breakpoints gutter above */
+}
+
+.CodeMirror-foldgutter-open,
+.CodeMirror-foldgutter-folded {
+ height: 14px;
+ margin-top: 1px;
+ background-image: url("chrome://devtools/skin/images/arrow.svg");
+ background-position: center;
+ background-repeat: no-repeat;
+ -moz-context-properties: fill;
+ fill: var(--theme-icon-dimmed-color);
+ /* make the icons smaller than regular twistys (10->8px) */
+ background-size: 8px;
+ cursor: pointer;
+}
+
+.CodeMirror-foldgutter-folded {
+ transform: rotate(-90deg);
+}
+
+.CodeMirror-hints {
+ position: absolute;
+ z-index: 10;
+ overflow: hidden;
+ list-style: none;
+ margin: 0;
+ padding: 2px;
+ border-radius: 3px;
+ font-size: 90%;
+ max-height: 20em;
+ overflow-y: auto;
+}
+
+.CodeMirror-hint {
+ margin: 0;
+ padding: 0 4px;
+ border-radius: 2px;
+ max-width: 19em;
+ overflow: hidden;
+ white-space: pre;
+ cursor: pointer;
+}
+
+.CodeMirror-Tern-completion {
+ padding-inline-start: 22px;
+ position: relative;
+ line-height: 18px;
+}
+
+.CodeMirror-Tern-completion:before {
+ position: absolute;
+ left: 2px;
+ bottom: 2px;
+ border-radius: 50%;
+ font-size: 12px;
+ font-weight: bold;
+ height: 15px;
+ width: 15px;
+ line-height: 16px;
+ text-align: center;
+ color: #ffffff;
+ box-sizing: border-box;
+}
+
+.CodeMirror-Tern-completion-unknown:before {
+ content: "?";
+}
+
+.CodeMirror-Tern-completion-object:before {
+ content: "O";
+}
+
+.CodeMirror-Tern-completion-fn:before {
+ content: "F";
+}
+
+.CodeMirror-Tern-completion-array:before {
+ content: "A";
+}
+
+.CodeMirror-Tern-completion-number:before {
+ content: "N";
+}
+
+.CodeMirror-Tern-completion-string:before {
+ content: "S";
+}
+
+.CodeMirror-Tern-completion-bool:before {
+ content: "B";
+}
+
+.CodeMirror-Tern-completion-guess {
+ color: #999;
+}
+
+.CodeMirror-Tern-tooltip {
+ border-radius: 3px;
+ padding: 2px 5px;
+ white-space: pre-wrap;
+ max-width: 40em;
+ position: absolute;
+ z-index: 10;
+}
+
+.CodeMirror-Tern-hint-doc {
+ max-width: 25em;
+}
+
+.CodeMirror-Tern-farg-current {
+ text-decoration: underline;
+}
+
+.CodeMirror-Tern-fhint-guess {
+ opacity: .7;
+}
+
+/* Override the background-color: white applied to filler elements in codemirror.css */
+.CodeMirror-scrollbar-filler, .CodeMirror-gutter-filler {
+ appearance: auto;
+ -moz-default-appearance: scrollcorner;
+}
+
+/* Markup view and Event tooltip styles */
+
+.CodeMirror.cm-s-markup-view pre {
+ font-size: var(--theme-code-font-size);
+ line-height: var(--theme-code-line-height);
+ min-height: 15px;
+}
+
+/* Make our own cursor-blink animation */
+@keyframes cursor-blink {
+ 0% {}
+ 50% { opacity: 0; }
+ 100% {}
+}
+
+.CodeMirror-focused .CodeMirror-cursor {
+ /*
+ * We're using the --caret-blink-time custom property for the animation duration.
+ * It is set in editor.js when we setup the CodeMirror instance, and will map either
+ * to the value of the ui.caretBlinkTime preference, or to CodeMirror's default for
+ * cursorBlinkRate. (See Bug 1609567 for more information on why this is needed).
+ */
+ /*
+ * The animation should only be set when the editor is focused, otherwise the
+ * animation will continue even when devtools is in a background tab.
+ * This happens because the cursor is hidden using visiblity: hidden rather than
+ * display: none in codemirror.css. See bug 1661054 for details.
+ */
+ animation: cursor-blink calc(var(--caret-blink-time, 0.53s) * 2) steps(1) infinite;
+}
+
+
+/*
+ * Always align CodeMirror lines to the left.
+ * See Bug 1651443 for more information.
+ */
+.CodeMirror-lines {
+ text-align: left;
+}
+
+/* CodeMirror matchhighlight styling */
+.cm-matchhighlight {
+ outline: 1px solid var(--theme-contrast-border);
+ border-radius: 2px;
+}
+
+.cm-non-printable-char {
+ color: var(--theme-comment);
+ font-size: 0.9em;
+ border-radius: 2px;
+ outline: 1px solid currentColor;
+ margin-inline: 2px;
+ padding-inline: 2px;
+}
+
+/****************************************/
+/***** CodeMirror 6 specific styles *****/
+/****************************************/
+
+.cm-editor {
+ max-height: 100%;
+ height: 100%;
+}
+.cm-editor .cm-selectionBackground {
+ background: var(--theme-selection-background) !important;
+}
+
+.cm6-dt-foldgutter__toggle-button {
+ height: 14px;
+ width: 14px;
+ margin-inline: 3px;
+ /* By default, the icon is a bit too low */
+ translate: 0px -4px;
+ background-image: url("chrome://devtools/skin/images/arrow.svg");
+ background-position: center;
+ background-repeat: no-repeat;
+ background-color: transparent;
+ border: none;
+ -moz-context-properties: fill;
+ fill: var(--theme-icon-dimmed-color);
+ /* make the icons smaller than regular twistys (10->8px) */
+ background-size: 8px;
+ cursor: pointer;
+
+ &[aria-expanded=false] {
+ transform: rotate(-90deg);
+ }
+}
+
+.cm-editor .cm-foldPlaceholder {
+ font-family: sans-serif;
+ padding: 0 2px;
+ border-radius: 3px;
+ border: solid 1px var(--theme-splitter-color);
+ color: var(--theme-body-color);
+ background-color: var(--theme-sidebar-background);
+ vertical-align: middle;
+}
diff --git a/devtools/client/shared/sourceeditor/codemirror6/codemirror6.bundle.js b/devtools/client/shared/sourceeditor/codemirror6/codemirror6.bundle.js
new file mode 100644
index 0000000000..cbedb3ca53
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror6/codemirror6.bundle.js
@@ -0,0 +1 @@
+var CodeMirror=function(t){"use strict";class e{lineAt(t){if(t<0||t>this.length)throw new RangeError(`Invalid position ${t} in document of length ${this.length}`);return this.lineInner(t,!1,1,0)}line(t){if(t<1||t>this.lines)throw new RangeError(`Invalid line number ${t} in ${this.lines}-line document`);return this.lineInner(t,!0,1,0)}replace(t,e,i){[t,e]=c(this,t,e);let s=[];return this.decompose(0,t,s,2),i.length&&i.decompose(0,i.length,s,3),this.decompose(e,this.length,s,1),n.from(s,this.length-(e-t)+i.length)}append(t){return this.replace(this.length,this.length,t)}slice(t,e=this.length){[t,e]=c(this,t,e);let i=[];return this.decompose(t,e,i,0),n.from(i,e-t)}eq(t){if(t==this)return!0;if(t.length!=this.length||t.lines!=this.lines)return!1;let e=this.scanIdentical(t,1),i=this.length-this.scanIdentical(t,-1),n=new o(this),s=new o(t);for(let t=e,r=e;;){if(n.next(t),s.next(t),t=0,n.lineBreak!=s.lineBreak||n.done!=s.done||n.value!=s.value)return!1;if(r+=n.value.length,n.done||r>=i)return!0}}iter(t=1){return new o(this,t)}iterRange(t,e=this.length){return new a(this,t,e)}iterLines(t,e){let i;if(null==t)i=this.iter();else{null==e&&(e=this.lines+1);let n=this.line(t).from;i=this.iterRange(n,Math.max(n,e==this.lines+1?this.length:e<=1?0:this.line(e-1).to))}return new l(i)}toString(){return this.sliceString(0)}toJSON(){let t=[];return this.flatten(t),t}constructor(){}static of(t){if(0==t.length)throw new RangeError("A document must have at least one line");return 1!=t.length||t[0]?t.length<=32?new i(t):n.from(i.split(t,[])):e.empty}}class i extends e{constructor(t,e=function(t){let e=-1;for(let i of t)e+=i.length+1;return e}(t)){super(),this.text=t,this.length=e}get lines(){return this.text.length}get children(){return null}lineInner(t,e,i,n){for(let s=0;;s++){let r=this.text[s],o=n+r.length;if((e?i:o)>=t)return new h(n,o,i,r);n=o+1,i++}}decompose(t,e,n,o){let a=t<=0&&e>=this.length?this:new i(r(this.text,t,e),Math.min(e,this.length)-Math.max(0,t));if(1&o){let t=n.pop(),e=s(a.text,t.text.slice(),0,a.length);if(e.length<=32)n.push(new i(e,t.length+a.length));else{let t=e.length>>1;n.push(new i(e.slice(0,t)),new i(e.slice(t)))}}else n.push(a)}replace(t,e,o){if(!(o instanceof i))return super.replace(t,e,o);[t,e]=c(this,t,e);let a=s(this.text,s(o.text,r(this.text,0,t)),e),l=this.length+o.length-(e-t);return a.length<=32?new i(a,l):n.from(i.split(a,[]),l)}sliceString(t,e=this.length,i="\n"){[t,e]=c(this,t,e);let n="";for(let s=0,r=0;s<=e&&r<this.text.length;r++){let o=this.text[r],a=s+o.length;s>t&&r&&(n+=i),t<a&&e>s&&(n+=o.slice(Math.max(0,t-s),e-s)),s=a+1}return n}flatten(t){for(let e of this.text)t.push(e)}scanIdentical(){return 0}static split(t,e){let n=[],s=-1;for(let r of t)n.push(r),s+=r.length+1,32==n.length&&(e.push(new i(n,s)),n=[],s=-1);return s>-1&&e.push(new i(n,s)),e}}class n extends e{constructor(t,e){super(),this.children=t,this.length=e,this.lines=0;for(let e of t)this.lines+=e.lines}lineInner(t,e,i,n){for(let s=0;;s++){let r=this.children[s],o=n+r.length,a=i+r.lines-1;if((e?a:o)>=t)return r.lineInner(t,e,i,n);n=o+1,i=a+1}}decompose(t,e,i,n){for(let s=0,r=0;r<=e&&s<this.children.length;s++){let o=this.children[s],a=r+o.length;if(t<=a&&e>=r){let s=n&((r<=t?1:0)|(a>=e?2:0));r>=t&&a<=e&&!s?i.push(o):o.decompose(t-r,e-r,i,s)}r=a+1}}replace(t,e,i){if([t,e]=c(this,t,e),i.lines<this.lines)for(let s=0,r=0;s<this.children.length;s++){let o=this.children[s],a=r+o.length;if(t>=r&&e<=a){let l=o.replace(t-r,e-r,i),h=this.lines-o.lines+l.lines;if(l.lines<h>>4&&l.lines>h>>6){let r=this.children.slice();return r[s]=l,new n(r,this.length-(e-t)+i.length)}return super.replace(r,a,l)}r=a+1}return super.replace(t,e,i)}sliceString(t,e=this.length,i="\n"){[t,e]=c(this,t,e);let n="";for(let s=0,r=0;s<this.children.length&&r<=e;s++){let o=this.children[s],a=r+o.length;r>t&&s&&(n+=i),t<a&&e>r&&(n+=o.sliceString(t-r,e-r,i)),r=a+1}return n}flatten(t){for(let e of this.children)e.flatten(t)}scanIdentical(t,e){if(!(t instanceof n))return 0;let i=0,[s,r,o,a]=e>0?[0,0,this.children.length,t.children.length]:[this.children.length-1,t.children.length-1,-1,-1];for(;;s+=e,r+=e){if(s==o||r==a)return i;let n=this.children[s],l=t.children[r];if(n!=l)return i+n.scanIdentical(l,e);i+=n.length+1}}static from(t,e=t.reduce(((t,e)=>t+e.length+1),-1)){let s=0;for(let e of t)s+=e.lines;if(s<32){let n=[];for(let e of t)e.flatten(n);return new i(n,e)}let r=Math.max(32,s>>5),o=r<<1,a=r>>1,l=[],h=0,c=-1,f=[];function u(t){let e;if(t.lines>o&&t instanceof n)for(let e of t.children)u(e);else t.lines>a&&(h>a||!h)?(d(),l.push(t)):t instanceof i&&h&&(e=f[f.length-1])instanceof i&&t.lines+e.lines<=32?(h+=t.lines,c+=t.length+1,f[f.length-1]=new i(e.text.concat(t.text),e.length+1+t.length)):(h+t.lines>r&&d(),h+=t.lines,c+=t.length+1,f.push(t))}function d(){0!=h&&(l.push(1==f.length?f[0]:n.from(f,c)),c=-1,h=f.length=0)}for(let e of t)u(e);return d(),1==l.length?l[0]:new n(l,e)}}function s(t,e,i=0,n=1e9){for(let s=0,r=0,o=!0;r<t.length&&s<=n;r++){let a=t[r],l=s+a.length;l>=i&&(l>n&&(a=a.slice(0,n-s)),s<i&&(a=a.slice(i-s)),o?(e[e.length-1]+=a,o=!1):e.push(a)),s=l+1}return e}function r(t,e,i){return s(t,[""],e,i)}e.empty=new i([""],0);class o{constructor(t,e=1){this.dir=e,this.done=!1,this.lineBreak=!1,this.value="",this.nodes=[t],this.offsets=[e>0?1:(t instanceof i?t.text.length:t.children.length)<<1]}nextInner(t,e){for(this.done=this.lineBreak=!1;;){let n=this.nodes.length-1,s=this.nodes[n],r=this.offsets[n],o=r>>1,a=s instanceof i?s.text.length:s.children.length;if(o==(e>0?a:0)){if(0==n)return this.done=!0,this.value="",this;e>0&&this.offsets[n-1]++,this.nodes.pop(),this.offsets.pop()}else if((1&r)==(e>0?0:1)){if(this.offsets[n]+=e,0==t)return this.lineBreak=!0,this.value="\n",this;t--}else if(s instanceof i){let i=s.text[o+(e<0?-1:0)];if(this.offsets[n]+=e,i.length>Math.max(0,t))return this.value=0==t?i:e>0?i.slice(t):i.slice(0,i.length-t),this;t-=i.length}else{let r=s.children[o+(e<0?-1:0)];t>r.length?(t-=r.length,this.offsets[n]+=e):(e<0&&this.offsets[n]--,this.nodes.push(r),this.offsets.push(e>0?1:(r instanceof i?r.text.length:r.children.length)<<1))}}}next(t=0){return t<0&&(this.nextInner(-t,-this.dir),t=this.value.length),this.nextInner(t,this.dir)}}class a{constructor(t,e,i){this.value="",this.done=!1,this.cursor=new o(t,e>i?-1:1),this.pos=e>i?t.length:0,this.from=Math.min(e,i),this.to=Math.max(e,i)}nextInner(t,e){if(e<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;t+=Math.max(0,e<0?this.pos-this.to:this.from-this.pos);let i=e<0?this.pos-this.from:this.to-this.pos;t>i&&(t=i),i-=t;let{value:n}=this.cursor.next(t);return this.pos+=(n.length+t)*e,this.value=n.length<=i?n:e<0?n.slice(n.length-i):n.slice(0,i),this.done=!this.value,this}next(t=0){return t<0?t=Math.max(t,this.from-this.pos):t>0&&(t=Math.min(t,this.to-this.pos)),this.nextInner(t,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&""!=this.value}}class l{constructor(t){this.inner=t,this.afterBreak=!0,this.value="",this.done=!1}next(t=0){let{done:e,lineBreak:i,value:n}=this.inner.next(t);return e&&this.afterBreak?(this.value="",this.afterBreak=!1):e?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=n,this.afterBreak=!1),this}get lineBreak(){return!1}}"undefined"!=typeof Symbol&&(e.prototype[Symbol.iterator]=function(){return this.iter()},o.prototype[Symbol.iterator]=a.prototype[Symbol.iterator]=l.prototype[Symbol.iterator]=function(){return this});class h{constructor(t,e,i,n){this.from=t,this.to=e,this.number=i,this.text=n}get length(){return this.to-this.from}}function c(t,e,i){return[e=Math.max(0,Math.min(t.length,e)),Math.max(e,Math.min(t.length,i))]}let f="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map((t=>t?parseInt(t,36):1));for(let t=1;t<f.length;t++)f[t]+=f[t-1];function u(t){for(let e=1;e<f.length;e+=2)if(f[e]>t)return f[e-1]<=t;return!1}function d(t){return t>=127462&&t<=127487}const p=8205;function O(t,e,i=!0,n=!0){return(i?g:m)(t,e,n)}function g(t,e,i){if(e==t.length)return e;e&&w(t.charCodeAt(e))&&v(t.charCodeAt(e-1))&&e--;let n=b(t,e);for(e+=S(n);e<t.length;){let s=b(t,e);if(n==p||s==p||i&&u(s))e+=S(s),n=s;else{if(!d(s))break;{let i=0,n=e-2;for(;n>=0&&d(b(t,n));)i++,n-=2;if(i%2==0)break;e+=2}}}return e}function m(t,e,i){for(;e>0;){let n=g(t,e-2,i);if(n<e)return n;e--}return 0}function w(t){return t>=56320&&t<57344}function v(t){return t>=55296&&t<56320}function b(t,e){let i=t.charCodeAt(e);if(!v(i)||e+1==t.length)return i;let n=t.charCodeAt(e+1);return w(n)?n-56320+(i-55296<<10)+65536:i}function y(t){return t<=65535?String.fromCharCode(t):(t-=65536,String.fromCharCode(55296+(t>>10),56320+(1023&t)))}function S(t){return t<65536?1:2}const x=/\r\n?|\n/;var k=function(t){return t[t.Simple=0]="Simple",t[t.TrackDel=1]="TrackDel",t[t.TrackBefore=2]="TrackBefore",t[t.TrackAfter=3]="TrackAfter",t}(k||(k={}));class Q{constructor(t){this.sections=t}get length(){let t=0;for(let e=0;e<this.sections.length;e+=2)t+=this.sections[e];return t}get newLength(){let t=0;for(let e=0;e<this.sections.length;e+=2){let i=this.sections[e+1];t+=i<0?this.sections[e]:i}return t}get empty(){return 0==this.sections.length||2==this.sections.length&&this.sections[1]<0}iterGaps(t){for(let e=0,i=0,n=0;e<this.sections.length;){let s=this.sections[e++],r=this.sections[e++];r<0?(t(i,n,s),n+=s):n+=r,i+=s}}iterChangedRanges(t,e=!1){C(this,t,e)}get invertedDesc(){let t=[];for(let e=0;e<this.sections.length;){let i=this.sections[e++],n=this.sections[e++];n<0?t.push(i,n):t.push(n,i)}return new Q(t)}composeDesc(t){return this.empty?t:t.empty?this:A(this,t)}mapDesc(t,e=!1){return t.empty?this:T(this,t,e)}mapPos(t,e=-1,i=k.Simple){let n=0,s=0;for(let r=0;r<this.sections.length;){let o=this.sections[r++],a=this.sections[r++],l=n+o;if(a<0){if(l>t)return s+(t-n);s+=o}else{if(i!=k.Simple&&l>=t&&(i==k.TrackDel&&n<t&&l>t||i==k.TrackBefore&&n<t||i==k.TrackAfter&&l>t))return null;if(l>t||l==t&&e<0&&!o)return t==n||e<0?s:s+a;s+=a}n=l}if(t>n)throw new RangeError(`Position ${t} is out of range for changeset of length ${n}`);return s}touchesRange(t,e=t){for(let i=0,n=0;i<this.sections.length&&n<=e;){let s=n+this.sections[i++];if(this.sections[i++]>=0&&n<=e&&s>=t)return!(n<t&&s>e)||"cover";n=s}return!1}toString(){let t="";for(let e=0;e<this.sections.length;){let i=this.sections[e++],n=this.sections[e++];t+=(t?" ":"")+i+(n>=0?":"+n:"")}return t}toJSON(){return this.sections}static fromJSON(t){if(!Array.isArray(t)||t.length%2||t.some((t=>"number"!=typeof t)))throw new RangeError("Invalid JSON representation of ChangeDesc");return new Q(t)}static create(t){return new Q(t)}}class $ extends Q{constructor(t,e){super(t),this.inserted=e}apply(t){if(this.length!=t.length)throw new RangeError("Applying change set to a document with the wrong length");return C(this,((e,i,n,s,r)=>t=t.replace(n,n+(i-e),r)),!1),t}mapDesc(t,e=!1){return T(this,t,e,!0)}invert(t){let i=this.sections.slice(),n=[];for(let s=0,r=0;s<i.length;s+=2){let o=i[s],a=i[s+1];if(a>=0){i[s]=a,i[s+1]=o;let l=s>>1;for(;n.length<l;)n.push(e.empty);n.push(o?t.slice(r,r+o):e.empty)}r+=o}return new $(i,n)}compose(t){return this.empty?t:t.empty?this:A(this,t,!0)}map(t,e=!1){return t.empty?this:T(this,t,e,!0)}iterChanges(t,e=!1){C(this,t,e)}get desc(){return Q.create(this.sections)}filter(t){let e=[],i=[],n=[],s=new R(this);t:for(let r=0,o=0;;){let a=r==t.length?1e9:t[r++];for(;o<a||o==a&&0==s.len;){if(s.done)break t;let t=Math.min(s.len,a-o);P(n,t,-1);let r=-1==s.ins?-1:0==s.off?s.ins:0;P(e,t,r),r>0&&Z(i,e,s.text),s.forward(t),o+=t}let l=t[r++];for(;o<l;){if(s.done)break t;let t=Math.min(s.len,l-o);P(e,t,-1),P(n,t,-1==s.ins?-1:0==s.off?s.ins:0),s.forward(t),o+=t}}return{changes:new $(e,i),filtered:Q.create(n)}}toJSON(){let t=[];for(let e=0;e<this.sections.length;e+=2){let i=this.sections[e],n=this.sections[e+1];n<0?t.push(i):0==n?t.push([i]):t.push([i].concat(this.inserted[e>>1].toJSON()))}return t}static of(t,i,n){let s=[],r=[],o=0,a=null;function l(t=!1){if(!t&&!s.length)return;o<i&&P(s,i-o,-1);let e=new $(s,r);a=a?a.compose(e.map(a)):e,s=[],r=[],o=0}return function t(h){if(Array.isArray(h))for(let e of h)t(e);else if(h instanceof $){if(h.length!=i)throw new RangeError(`Mismatched change set length (got ${h.length}, expected ${i})`);l(),a=a?a.compose(h.map(a)):h}else{let{from:t,to:a=t,insert:c}=h;if(t>a||t<0||a>i)throw new RangeError(`Invalid change range ${t} to ${a} (in doc of length ${i})`);let f=c?"string"==typeof c?e.of(c.split(n||x)):c:e.empty,u=f.length;if(t==a&&0==u)return;t<o&&l(),t>o&&P(s,t-o,-1),P(s,a-t,u),Z(r,s,f),o=a}}(t),l(!a),a}static empty(t){return new $(t?[t,-1]:[],[])}static fromJSON(t){if(!Array.isArray(t))throw new RangeError("Invalid JSON representation of ChangeSet");let i=[],n=[];for(let s=0;s<t.length;s++){let r=t[s];if("number"==typeof r)i.push(r,-1);else{if(!Array.isArray(r)||"number"!=typeof r[0]||r.some(((t,e)=>e&&"string"!=typeof t)))throw new RangeError("Invalid JSON representation of ChangeSet");if(1==r.length)i.push(r[0],0);else{for(;n.length<s;)n.push(e.empty);n[s]=e.of(r.slice(1)),i.push(r[0],n[s].length)}}}return new $(i,n)}static createSet(t,e){return new $(t,e)}}function P(t,e,i,n=!1){if(0==e&&i<=0)return;let s=t.length-2;s>=0&&i<=0&&i==t[s+1]?t[s]+=e:0==e&&0==t[s]?t[s+1]+=i:n?(t[s]+=e,t[s+1]+=i):t.push(e,i)}function Z(t,i,n){if(0==n.length)return;let s=i.length-2>>1;if(s<t.length)t[t.length-1]=t[t.length-1].append(n);else{for(;t.length<s;)t.push(e.empty);t.push(n)}}function C(t,i,n){let s=t.inserted;for(let r=0,o=0,a=0;a<t.sections.length;){let l=t.sections[a++],h=t.sections[a++];if(h<0)r+=l,o+=l;else{let c=r,f=o,u=e.empty;for(;c+=l,f+=h,h&&s&&(u=u.append(s[a-2>>1])),!(n||a==t.sections.length||t.sections[a+1]<0);)l=t.sections[a++],h=t.sections[a++];i(r,c,o,f,u),r=c,o=f}}}function T(t,e,i,n=!1){let s=[],r=n?[]:null,o=new R(t),a=new R(e);for(let t=-1;;)if(-1==o.ins&&-1==a.ins){let t=Math.min(o.len,a.len);P(s,t,-1),o.forward(t),a.forward(t)}else if(a.ins>=0&&(o.ins<0||t==o.i||0==o.off&&(a.len<o.len||a.len==o.len&&!i))){let e=a.len;for(P(s,a.ins,-1);e;){let i=Math.min(o.len,e);o.ins>=0&&t<o.i&&o.len<=i&&(P(s,0,o.ins),r&&Z(r,s,o.text),t=o.i),o.forward(i),e-=i}a.next()}else{if(!(o.ins>=0)){if(o.done&&a.done)return r?$.createSet(s,r):Q.create(s);throw new Error("Mismatched change set lengths")}{let e=0,i=o.len;for(;i;)if(-1==a.ins){let t=Math.min(i,a.len);e+=t,i-=t,a.forward(t)}else{if(!(0==a.ins&&a.len<i))break;i-=a.len,a.next()}P(s,e,t<o.i?o.ins:0),r&&t<o.i&&Z(r,s,o.text),t=o.i,o.forward(o.len-i)}}}function A(t,e,i=!1){let n=[],s=i?[]:null,r=new R(t),o=new R(e);for(let t=!1;;){if(r.done&&o.done)return s?$.createSet(n,s):Q.create(n);if(0==r.ins)P(n,r.len,0,t),r.next();else if(0!=o.len||o.done){if(r.done||o.done)throw new Error("Mismatched change set lengths");{let e=Math.min(r.len2,o.len),i=n.length;if(-1==r.ins){let i=-1==o.ins?-1:o.off?0:o.ins;P(n,e,i,t),s&&i&&Z(s,n,o.text)}else-1==o.ins?(P(n,r.off?0:r.len,e,t),s&&Z(s,n,r.textBit(e))):(P(n,r.off?0:r.len,o.off?0:o.ins,t),s&&!o.off&&Z(s,n,o.text));t=(r.ins>e||o.ins>=0&&o.len>e)&&(t||n.length>i),r.forward2(e),o.forward(e)}}else P(n,0,o.ins,t),s&&Z(s,n,o.text),o.next()}}class R{constructor(t){this.set=t,this.i=0,this.next()}next(){let{sections:t}=this.set;this.i<t.length?(this.len=t[this.i++],this.ins=t[this.i++]):(this.len=0,this.ins=-2),this.off=0}get done(){return-2==this.ins}get len2(){return this.ins<0?this.len:this.ins}get text(){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length?e.empty:t[i]}textBit(t){let{inserted:i}=this.set,n=this.i-2>>1;return n>=i.length&&!t?e.empty:i[n].slice(this.off,null==t?void 0:this.off+t)}forward(t){t==this.len?this.next():(this.len-=t,this.off+=t)}forward2(t){-1==this.ins?this.forward(t):t==this.ins?this.next():(this.ins-=t,this.off+=t)}}class X{constructor(t,e,i){this.from=t,this.to=e,this.flags=i}get anchor(){return 32&this.flags?this.to:this.from}get head(){return 32&this.flags?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return 8&this.flags?-1:16&this.flags?1:0}get bidiLevel(){let t=7&this.flags;return 7==t?null:t}get goalColumn(){let t=this.flags>>6;return 16777215==t?void 0:t}map(t,e=-1){let i,n;return this.empty?i=n=t.mapPos(this.from,e):(i=t.mapPos(this.from,1),n=t.mapPos(this.to,-1)),i==this.from&&n==this.to?this:new X(i,n,this.flags)}extend(t,e=t){if(t<=this.anchor&&e>=this.anchor)return Y.range(t,e);let i=Math.abs(t-this.anchor)>Math.abs(e-this.anchor)?t:e;return Y.range(this.anchor,i)}eq(t,e=!1){return!(this.anchor!=t.anchor||this.head!=t.head||e&&this.empty&&this.assoc!=t.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(t){if(!t||"number"!=typeof t.anchor||"number"!=typeof t.head)throw new RangeError("Invalid JSON representation for SelectionRange");return Y.range(t.anchor,t.head)}static create(t,e,i){return new X(t,e,i)}}class Y{constructor(t,e){this.ranges=t,this.mainIndex=e}map(t,e=-1){return t.empty?this:Y.create(this.ranges.map((i=>i.map(t,e))),this.mainIndex)}eq(t,e=!1){if(this.ranges.length!=t.ranges.length||this.mainIndex!=t.mainIndex)return!1;for(let i=0;i<this.ranges.length;i++)if(!this.ranges[i].eq(t.ranges[i],e))return!1;return!0}get main(){return this.ranges[this.mainIndex]}asSingle(){return 1==this.ranges.length?this:new Y([this.main],0)}addRange(t,e=!0){return Y.create([t].concat(this.ranges),e?0:this.mainIndex+1)}replaceRange(t,e=this.mainIndex){let i=this.ranges.slice();return i[e]=t,Y.create(i,this.mainIndex)}toJSON(){return{ranges:this.ranges.map((t=>t.toJSON())),main:this.mainIndex}}static fromJSON(t){if(!t||!Array.isArray(t.ranges)||"number"!=typeof t.main||t.main>=t.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new Y(t.ranges.map((t=>X.fromJSON(t))),t.main)}static single(t,e=t){return new Y([Y.range(t,e)],0)}static create(t,e=0){if(0==t.length)throw new RangeError("A selection needs at least one range");for(let i=0,n=0;n<t.length;n++){let s=t[n];if(s.empty?s.from<=i:s.from<i)return Y.normalized(t.slice(),e);i=s.to}return new Y(t,e)}static cursor(t,e=0,i,n){return X.create(t,t,(0==e?0:e<0?8:16)|(null==i?7:Math.min(6,i))|(null!=n?n:16777215)<<6)}static range(t,e,i,n){let s=(null!=i?i:16777215)<<6|(null==n?7:Math.min(6,n));return e<t?X.create(e,t,48|s):X.create(t,e,(e>t?8:0)|s)}static normalized(t,e=0){let i=t[e];t.sort(((t,e)=>t.from-e.from)),e=t.indexOf(i);for(let i=1;i<t.length;i++){let n=t[i],s=t[i-1];if(n.empty?n.from<=s.to:n.from<s.to){let r=s.from,o=Math.max(n.to,s.to);i<=e&&e--,t.splice(--i,2,n.anchor>n.head?Y.range(o,r):Y.range(r,o))}}return new Y(t,e)}}function W(t,e){for(let i of t.ranges)if(i.to>e)throw new RangeError("Selection points outside of document")}let M=0;class j{constructor(t,e,i,n,s){this.combine=t,this.compareInput=e,this.compare=i,this.isStatic=n,this.id=M++,this.default=t([]),this.extensions="function"==typeof s?s(this):s}get reader(){return this}static define(t={}){return new j(t.combine||(t=>t),t.compareInput||((t,e)=>t===e),t.compare||(t.combine?(t,e)=>t===e:D),!!t.static,t.enables)}of(t){return new E([],this,0,t)}compute(t,e){if(this.isStatic)throw new Error("Can't compute a static facet");return new E(t,this,1,e)}computeN(t,e){if(this.isStatic)throw new Error("Can't compute a static facet");return new E(t,this,2,e)}from(t,e){return e||(e=t=>t),this.compute([t],(i=>e(i.field(t))))}}function D(t,e){return t==e||t.length==e.length&&t.every(((t,i)=>t===e[i]))}class E{constructor(t,e,i,n){this.dependencies=t,this.facet=e,this.type=i,this.value=n,this.id=M++}dynamicSlot(t){var e;let i=this.value,n=this.facet.compareInput,s=this.id,r=t[s]>>1,o=2==this.type,a=!1,l=!1,h=[];for(let i of this.dependencies)"doc"==i?a=!0:"selection"==i?l=!0:0==(1&(null!==(e=t[i.id])&&void 0!==e?e:1))&&h.push(t[i.id]);return{create:t=>(t.values[r]=i(t),1),update(t,e){if(a&&e.docChanged||l&&(e.docChanged||e.selection)||_(t,h)){let e=i(t);if(o?!q(e,t.values[r],n):!n(e,t.values[r]))return t.values[r]=e,1}return 0},reconfigure:(t,e)=>{let a,l=e.config.address[s];if(null!=l){let s=it(e,l);if(this.dependencies.every((i=>i instanceof j?e.facet(i)===t.facet(i):!(i instanceof z)||e.field(i,!1)==t.field(i,!1)))||(o?q(a=i(t),s,n):n(a=i(t),s)))return t.values[r]=s,0}else a=i(t);return t.values[r]=a,1}}}}function q(t,e,i){if(t.length!=e.length)return!1;for(let n=0;n<t.length;n++)if(!i(t[n],e[n]))return!1;return!0}function _(t,e){let i=!1;for(let n of e)1&et(t,n)&&(i=!0);return i}function V(t,e,i){let n=i.map((e=>t[e.id])),s=i.map((t=>t.type)),r=n.filter((t=>!(1&t))),o=t[e.id]>>1;function a(t){let i=[];for(let e=0;e<n.length;e++){let r=it(t,n[e]);if(2==s[e])for(let t of r)i.push(t);else i.push(r)}return e.combine(i)}return{create(t){for(let e of n)et(t,e);return t.values[o]=a(t),1},update(t,i){if(!_(t,r))return 0;let n=a(t);return e.compare(n,t.values[o])?0:(t.values[o]=n,1)},reconfigure(t,s){let r=_(t,n),l=s.config.facets[e.id],h=s.facet(e);if(l&&!r&&D(i,l))return t.values[o]=h,0;let c=a(t);return e.compare(c,h)?(t.values[o]=h,0):(t.values[o]=c,1)}}}const I=j.define({static:!0});class z{constructor(t,e,i,n,s){this.id=t,this.createF=e,this.updateF=i,this.compareF=n,this.spec=s,this.provides=void 0}static define(t){let e=new z(M++,t.create,t.update,t.compare||((t,e)=>t===e),t);return t.provide&&(e.provides=t.provide(e)),e}create(t){let e=t.facet(I).find((t=>t.field==this));return((null==e?void 0:e.create)||this.createF)(t)}slot(t){let e=t[this.id]>>1;return{create:t=>(t.values[e]=this.create(t),1),update:(t,i)=>{let n=t.values[e],s=this.updateF(n,i);return this.compareF(n,s)?0:(t.values[e]=s,1)},reconfigure:(t,i)=>null!=i.config.address[this.id]?(t.values[e]=i.field(this),0):(t.values[e]=this.create(t),1)}}init(t){return[this,I.of({field:this,create:t})]}get extension(){return this}}const B=4,G=3,L=2,N=1;function U(t){return e=>new F(e,t)}const H={highest:U(0),high:U(N),default:U(L),low:U(G),lowest:U(B)};class F{constructor(t,e){this.inner=t,this.prec=e}}class J{of(t){return new K(this,t)}reconfigure(t){return J.reconfigure.of({compartment:this,extension:t})}get(t){return t.config.compartments.get(this)}}class K{constructor(t,e){this.compartment=t,this.inner=e}}class tt{constructor(t,e,i,n,s,r){for(this.base=t,this.compartments=e,this.dynamicSlots=i,this.address=n,this.staticValues=s,this.facets=r,this.statusTemplate=[];this.statusTemplate.length<i.length;)this.statusTemplate.push(0)}staticFacet(t){let e=this.address[t.id];return null==e?t.default:this.staticValues[e>>1]}static resolve(t,e,i){let n=[],s=Object.create(null),r=new Map;for(let i of function(t,e,i){let n=[[],[],[],[],[]],s=new Map;function r(t,o){let a=s.get(t);if(null!=a){if(a<=o)return;let e=n[a].indexOf(t);e>-1&&n[a].splice(e,1),t instanceof K&&i.delete(t.compartment)}if(s.set(t,o),Array.isArray(t))for(let e of t)r(e,o);else if(t instanceof K){if(i.has(t.compartment))throw new RangeError("Duplicate use of compartment in extensions");let n=e.get(t.compartment)||t.inner;i.set(t.compartment,n),r(n,o)}else if(t instanceof F)r(t.inner,t.prec);else if(t instanceof z)n[o].push(t),t.provides&&r(t.provides,o);else if(t instanceof E)n[o].push(t),t.facet.extensions&&r(t.facet.extensions,L);else{let e=t.extension;if(!e)throw new Error(`Unrecognized extension value in extension set (${t}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);r(e,o)}}return r(t,L),n.reduce(((t,e)=>t.concat(e)))}(t,e,r))i instanceof z?n.push(i):(s[i.facet.id]||(s[i.facet.id]=[])).push(i);let o=Object.create(null),a=[],l=[];for(let t of n)o[t.id]=l.length<<1,l.push((e=>t.slot(e)));let h=null==i?void 0:i.config.facets;for(let t in s){let e=s[t],n=e[0].facet,r=h&&h[t]||[];if(e.every((t=>0==t.type)))if(o[n.id]=a.length<<1|1,D(r,e))a.push(i.facet(n));else{let t=n.combine(e.map((t=>t.value)));a.push(i&&n.compare(t,i.facet(n))?i.facet(n):t)}else{for(let t of e)0==t.type?(o[t.id]=a.length<<1|1,a.push(t.value)):(o[t.id]=l.length<<1,l.push((e=>t.dynamicSlot(e))));o[n.id]=l.length<<1,l.push((t=>V(t,n,e)))}}let c=l.map((t=>t(o)));return new tt(t,r,c,o,a,s)}}function et(t,e){if(1&e)return 2;let i=e>>1,n=t.status[i];if(4==n)throw new Error("Cyclic dependency between fields and/or facets");if(2&n)return n;t.status[i]=4;let s=t.computeSlot(t,t.config.dynamicSlots[i]);return t.status[i]=2|s}function it(t,e){return 1&e?t.config.staticValues[e>>1]:t.values[e>>1]}const nt=j.define(),st=j.define({combine:t=>t.some((t=>t)),static:!0}),rt=j.define({combine:t=>t.length?t[0]:void 0,static:!0}),ot=j.define(),at=j.define(),lt=j.define(),ht=j.define({combine:t=>!!t.length&&t[0]});class ct{constructor(t,e){this.type=t,this.value=e}static define(){return new ft}}class ft{of(t){return new ct(this,t)}}class ut{constructor(t){this.map=t}of(t){return new dt(this,t)}}class dt{constructor(t,e){this.type=t,this.value=e}map(t){let e=this.type.map(this.value,t);return void 0===e?void 0:e==this.value?this:new dt(this.type,e)}is(t){return this.type==t}static define(t={}){return new ut(t.map||(t=>t))}static mapEffects(t,e){if(!t.length)return t;let i=[];for(let n of t){let t=n.map(e);t&&i.push(t)}return i}}dt.reconfigure=dt.define(),dt.appendConfig=dt.define();class pt{constructor(t,e,i,n,s,r){this.startState=t,this.changes=e,this.selection=i,this.effects=n,this.annotations=s,this.scrollIntoView=r,this._doc=null,this._state=null,i&&W(i,e.newLength),s.some((t=>t.type==pt.time))||(this.annotations=s.concat(pt.time.of(Date.now())))}static create(t,e,i,n,s,r){return new pt(t,e,i,n,s,r)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(t){for(let e of this.annotations)if(e.type==t)return e.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(t){let e=this.annotation(pt.userEvent);return!(!e||!(e==t||e.length>t.length&&e.slice(0,t.length)==t&&"."==e[t.length]))}}function Ot(t,e){let i=[];for(let n=0,s=0;;){let r,o;if(n<t.length&&(s==e.length||e[s]>=t[n]))r=t[n++],o=t[n++];else{if(!(s<e.length))return i;r=e[s++],o=e[s++]}!i.length||i[i.length-1]<r?i.push(r,o):i[i.length-1]<o&&(i[i.length-1]=o)}}function gt(t,e,i){var n;let s,r,o;return i?(s=e.changes,r=$.empty(e.changes.length),o=t.changes.compose(e.changes)):(s=e.changes.map(t.changes),r=t.changes.mapDesc(e.changes,!0),o=t.changes.compose(s)),{changes:o,selection:e.selection?e.selection.map(r):null===(n=t.selection)||void 0===n?void 0:n.map(s),effects:dt.mapEffects(t.effects,s).concat(dt.mapEffects(e.effects,r)),annotations:t.annotations.length?t.annotations.concat(e.annotations):e.annotations,scrollIntoView:t.scrollIntoView||e.scrollIntoView}}function mt(t,e,i){let n=e.selection,s=bt(e.annotations);return e.userEvent&&(s=s.concat(pt.userEvent.of(e.userEvent))),{changes:e.changes instanceof $?e.changes:$.of(e.changes||[],i,t.facet(rt)),selection:n&&(n instanceof Y?n:Y.single(n.anchor,n.head)),effects:bt(e.effects),annotations:s,scrollIntoView:!!e.scrollIntoView}}function wt(t,e,i){let n=mt(t,e.length?e[0]:{},t.doc.length);e.length&&!1===e[0].filter&&(i=!1);for(let s=1;s<e.length;s++){!1===e[s].filter&&(i=!1);let r=!!e[s].sequential;n=gt(n,mt(t,e[s],r?n.changes.newLength:t.doc.length),r)}let s=pt.create(t,n.changes,n.selection,n.effects,n.annotations,n.scrollIntoView);return function(t){let e=t.startState,i=e.facet(lt),n=t;for(let s=i.length-1;s>=0;s--){let r=i[s](t);r&&Object.keys(r).length&&(n=gt(n,mt(e,r,t.changes.newLength),!0))}return n==t?t:pt.create(e,t.changes,t.selection,n.effects,n.annotations,n.scrollIntoView)}(i?function(t){let e=t.startState,i=!0;for(let n of e.facet(ot)){let e=n(t);if(!1===e){i=!1;break}Array.isArray(e)&&(i=!0===i?e:Ot(i,e))}if(!0!==i){let n,s;if(!1===i)s=t.changes.invertedDesc,n=$.empty(e.doc.length);else{let e=t.changes.filter(i);n=e.changes,s=e.filtered.mapDesc(e.changes).invertedDesc}t=pt.create(e,n,t.selection&&t.selection.map(s),dt.mapEffects(t.effects,s),t.annotations,t.scrollIntoView)}let n=e.facet(at);for(let i=n.length-1;i>=0;i--){let s=n[i](t);t=s instanceof pt?s:Array.isArray(s)&&1==s.length&&s[0]instanceof pt?s[0]:wt(e,bt(s),!1)}return t}(s):s)}pt.time=ct.define(),pt.userEvent=ct.define(),pt.addToHistory=ct.define(),pt.remote=ct.define();const vt=[];function bt(t){return null==t?vt:Array.isArray(t)?t:[t]}var yt=function(t){return t[t.Word=0]="Word",t[t.Space=1]="Space",t[t.Other=2]="Other",t}(yt||(yt={}));const St=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let xt;try{xt=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch(t){}function kt(t){return e=>{if(!/\S/.test(e))return yt.Space;if(function(t){if(xt)return xt.test(t);for(let e=0;e<t.length;e++){let i=t[e];if(/\w/.test(i)||i>"€"&&(i.toUpperCase()!=i.toLowerCase()||St.test(i)))return!0}return!1}(e))return yt.Word;for(let i=0;i<t.length;i++)if(e.indexOf(t[i])>-1)return yt.Word;return yt.Other}}class Qt{constructor(t,e,i,n,s,r){this.config=t,this.doc=e,this.selection=i,this.values=n,this.status=t.statusTemplate.slice(),this.computeSlot=s,r&&(r._state=this);for(let t=0;t<this.config.dynamicSlots.length;t++)et(this,t<<1);this.computeSlot=null}field(t,e=!0){let i=this.config.address[t.id];if(null!=i)return et(this,i),it(this,i);if(e)throw new RangeError("Field is not present in this state")}update(...t){return wt(this,t,!0)}applyTransaction(t){let e,i=this.config,{base:n,compartments:s}=i;for(let e of t.effects)e.is(J.reconfigure)?(i&&(s=new Map,i.compartments.forEach(((t,e)=>s.set(e,t))),i=null),s.set(e.value.compartment,e.value.extension)):e.is(dt.reconfigure)?(i=null,n=e.value):e.is(dt.appendConfig)&&(i=null,n=bt(n).concat(e.value));if(i)e=t.startState.values.slice();else{i=tt.resolve(n,s,this),e=new Qt(i,this.doc,this.selection,i.dynamicSlots.map((()=>null)),((t,e)=>e.reconfigure(t,this)),null).values}let r=t.startState.facet(st)?t.newSelection:t.newSelection.asSingle();new Qt(i,t.newDoc,r,e,((e,i)=>i.update(e,t)),t)}replaceSelection(t){return"string"==typeof t&&(t=this.toText(t)),this.changeByRange((e=>({changes:{from:e.from,to:e.to,insert:t},range:Y.cursor(e.from+t.length)})))}changeByRange(t){let e=this.selection,i=t(e.ranges[0]),n=this.changes(i.changes),s=[i.range],r=bt(i.effects);for(let i=1;i<e.ranges.length;i++){let o=t(e.ranges[i]),a=this.changes(o.changes),l=a.map(n);for(let t=0;t<i;t++)s[t]=s[t].map(l);let h=n.mapDesc(a,!0);s.push(o.range.map(h)),n=n.compose(l),r=dt.mapEffects(r,l).concat(dt.mapEffects(bt(o.effects),h))}return{changes:n,selection:Y.create(s,e.mainIndex),effects:r}}changes(t=[]){return t instanceof $?t:$.of(t,this.doc.length,this.facet(Qt.lineSeparator))}toText(t){return e.of(t.split(this.facet(Qt.lineSeparator)||x))}sliceDoc(t=0,e=this.doc.length){return this.doc.sliceString(t,e,this.lineBreak)}facet(t){let e=this.config.address[t.id];return null==e?t.default:(et(this,e),it(this,e))}toJSON(t){let e={doc:this.sliceDoc(),selection:this.selection.toJSON()};if(t)for(let i in t){let n=t[i];n instanceof z&&null!=this.config.address[n.id]&&(e[i]=n.spec.toJSON(this.field(t[i]),this))}return e}static fromJSON(t,e={},i){if(!t||"string"!=typeof t.doc)throw new RangeError("Invalid JSON representation for EditorState");let n=[];if(i)for(let e in i)if(Object.prototype.hasOwnProperty.call(t,e)){let s=i[e],r=t[e];n.push(s.init((t=>s.spec.fromJSON(r,t))))}return Qt.create({doc:t.doc,selection:Y.fromJSON(t.selection),extensions:e.extensions?n.concat([e.extensions]):n})}static create(t={}){let i=tt.resolve(t.extensions||[],new Map),n=t.doc instanceof e?t.doc:e.of((t.doc||"").split(i.staticFacet(Qt.lineSeparator)||x)),s=t.selection?t.selection instanceof Y?t.selection:Y.single(t.selection.anchor,t.selection.head):Y.single(0);return W(s,n.length),i.staticFacet(st)||(s=s.asSingle()),new Qt(i,n,s,i.dynamicSlots.map((()=>null)),((t,e)=>e.create(t)),null)}get tabSize(){return this.facet(Qt.tabSize)}get lineBreak(){return this.facet(Qt.lineSeparator)||"\n"}get readOnly(){return this.facet(ht)}phrase(t,...e){for(let e of this.facet(Qt.phrases))if(Object.prototype.hasOwnProperty.call(e,t)){t=e[t];break}return e.length&&(t=t.replace(/\$(\$|\d*)/g,((t,i)=>{if("$"==i)return"$";let n=+(i||1);return!n||n>e.length?t:e[n-1]}))),t}languageDataAt(t,e,i=-1){let n=[];for(let s of this.facet(nt))for(let r of s(this,e,i))Object.prototype.hasOwnProperty.call(r,t)&&n.push(r[t]);return n}charCategorizer(t){return kt(this.languageDataAt("wordChars",t).join(""))}wordAt(t){let{text:e,from:i,length:n}=this.doc.lineAt(t),s=this.charCategorizer(t),r=t-i,o=t-i;for(;r>0;){let t=O(e,r,!1);if(s(e.slice(t,r))!=yt.Word)break;r=t}for(;o<n;){let t=O(e,o);if(s(e.slice(o,t))!=yt.Word)break;o=t}return r==o?null:Y.range(r+i,o+i)}}function $t(t,e,i={}){let n={};for(let e of t)for(let t of Object.keys(e)){let s=e[t],r=n[t];if(void 0===r)n[t]=s;else if(r===s||void 0===s);else{if(!Object.hasOwnProperty.call(i,t))throw new Error("Config merge conflict for field "+t);n[t]=i[t](r,s)}}for(let t in e)void 0===n[t]&&(n[t]=e[t]);return n}Qt.allowMultipleSelections=st,Qt.tabSize=j.define({combine:t=>t.length?t[0]:4}),Qt.lineSeparator=rt,Qt.readOnly=ht,Qt.phrases=j.define({compare(t,e){let i=Object.keys(t),n=Object.keys(e);return i.length==n.length&&i.every((i=>t[i]==e[i]))}}),Qt.languageData=nt,Qt.changeFilter=ot,Qt.transactionFilter=at,Qt.transactionExtender=lt,J.reconfigure=dt.define();class Pt{eq(t){return this==t}range(t,e=t){return Zt.create(t,e,this)}}Pt.prototype.startSide=Pt.prototype.endSide=0,Pt.prototype.point=!1,Pt.prototype.mapMode=k.TrackDel;let Zt=class t{constructor(t,e,i){this.from=t,this.to=e,this.value=i}static create(e,i,n){return new t(e,i,n)}};function Ct(t,e){return t.from-e.from||t.value.startSide-e.value.startSide}class Tt{constructor(t,e,i,n){this.from=t,this.to=e,this.value=i,this.maxPoint=n}get length(){return this.to[this.to.length-1]}findIndex(t,e,i,n=0){let s=i?this.to:this.from;for(let r=n,o=s.length;;){if(r==o)return r;let n=r+o>>1,a=s[n]-t||(i?this.value[n].endSide:this.value[n].startSide)-e;if(n==r)return a>=0?r:o;a>=0?o=n:r=n+1}}between(t,e,i,n){for(let s=this.findIndex(e,-1e9,!0),r=this.findIndex(i,1e9,!1,s);s<r;s++)if(!1===n(this.from[s]+t,this.to[s]+t,this.value[s]))return!1}map(t,e){let i=[],n=[],s=[],r=-1,o=-1;for(let a=0;a<this.value.length;a++){let l,h,c=this.value[a],f=this.from[a]+t,u=this.to[a]+t;if(f==u){let t=e.mapPos(f,c.startSide,c.mapMode);if(null==t)continue;if(l=h=t,c.startSide!=c.endSide&&(h=e.mapPos(f,c.endSide),h<l))continue}else if(l=e.mapPos(f,c.startSide),h=e.mapPos(u,c.endSide),l>h||l==h&&c.startSide>0&&c.endSide<=0)continue;(h-l||c.endSide-c.startSide)<0||(r<0&&(r=l),c.point&&(o=Math.max(o,h-l)),i.push(c),n.push(l-r),s.push(h-r))}return{mapped:i.length?new Tt(n,s,i,o):null,pos:r}}}class At{constructor(t,e,i,n){this.chunkPos=t,this.chunk=e,this.nextLayer=i,this.maxPoint=n}static create(t,e,i,n){return new At(t,e,i,n)}get length(){let t=this.chunk.length-1;return t<0?0:Math.max(this.chunkEnd(t),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let t=this.nextLayer.size;for(let e of this.chunk)t+=e.value.length;return t}chunkEnd(t){return this.chunkPos[t]+this.chunk[t].length}update(t){let{add:e=[],sort:i=!1,filterFrom:n=0,filterTo:s=this.length}=t,r=t.filter;if(0==e.length&&!r)return this;if(i&&(e=e.slice().sort(Ct)),this.isEmpty)return e.length?At.of(e):this;let o=new Yt(this,null,-1).goto(0),a=0,l=[],h=new Rt;for(;o.value||a<e.length;)if(a<e.length&&(o.from-e[a].from||o.startSide-e[a].value.startSide)>=0){let t=e[a++];h.addInner(t.from,t.to,t.value)||l.push(t)}else 1==o.rangeIndex&&o.chunkIndex<this.chunk.length&&(a==e.length||this.chunkEnd(o.chunkIndex)<e[a].from)&&(!r||n>this.chunkEnd(o.chunkIndex)||s<this.chunkPos[o.chunkIndex])&&h.addChunk(this.chunkPos[o.chunkIndex],this.chunk[o.chunkIndex])?o.nextChunk():((!r||n>o.to||s<o.from||r(o.from,o.to,o.value))&&(h.addInner(o.from,o.to,o.value)||l.push(Zt.create(o.from,o.to,o.value))),o.next());return h.finishInner(this.nextLayer.isEmpty&&!l.length?At.empty:this.nextLayer.update({add:l,filter:r,filterFrom:n,filterTo:s}))}map(t){if(t.empty||this.isEmpty)return this;let e=[],i=[],n=-1;for(let s=0;s<this.chunk.length;s++){let r=this.chunkPos[s],o=this.chunk[s],a=t.touchesRange(r,r+o.length);if(!1===a)n=Math.max(n,o.maxPoint),e.push(o),i.push(t.mapPos(r));else if(!0===a){let{mapped:s,pos:a}=o.map(r,t);s&&(n=Math.max(n,s.maxPoint),e.push(s),i.push(a))}}let s=this.nextLayer.map(t);return 0==e.length?s:new At(i,e,s||At.empty,n)}between(t,e,i){if(!this.isEmpty){for(let n=0;n<this.chunk.length;n++){let s=this.chunkPos[n],r=this.chunk[n];if(e>=s&&t<=s+r.length&&!1===r.between(s,t-s,e-s,i))return}this.nextLayer.between(t,e,i)}}iter(t=0){return Wt.from([this]).goto(t)}get isEmpty(){return this.nextLayer==this}static iter(t,e=0){return Wt.from(t).goto(e)}static compare(t,e,i,n,s=-1){let r=t.filter((t=>t.maxPoint>0||!t.isEmpty&&t.maxPoint>=s)),o=e.filter((t=>t.maxPoint>0||!t.isEmpty&&t.maxPoint>=s)),a=Xt(r,o,i),l=new jt(r,a,s),h=new jt(o,a,s);i.iterGaps(((t,e,i)=>Dt(l,t,h,e,i,n))),i.empty&&0==i.length&&Dt(l,0,h,0,0,n)}static eq(t,e,i=0,n){null==n&&(n=999999999);let s=t.filter((t=>!t.isEmpty&&e.indexOf(t)<0)),r=e.filter((e=>!e.isEmpty&&t.indexOf(e)<0));if(s.length!=r.length)return!1;if(!s.length)return!0;let o=Xt(s,r),a=new jt(s,o,0).goto(i),l=new jt(r,o,0).goto(i);for(;;){if(a.to!=l.to||!Et(a.active,l.active)||a.point&&(!l.point||!a.point.eq(l.point)))return!1;if(a.to>n)return!0;a.next(),l.next()}}static spans(t,e,i,n,s=-1){let r=new jt(t,null,s).goto(e),o=e,a=r.openStart;for(;;){let t=Math.min(r.to,i);if(r.point){let i=r.activeForPoint(r.to),s=r.pointFrom<e?i.length+1:Math.min(i.length,a);n.point(o,t,r.point,i,s,r.pointRank),a=Math.min(r.openEnd(t),i.length)}else t>o&&(n.span(o,t,r.active,a),a=r.openEnd(t));if(r.to>i)return a+(r.point&&r.to>i?1:0);o=r.to,r.next()}}static of(t,e=!1){let i=new Rt;for(let n of t instanceof Zt?[t]:e?function(t){if(t.length>1)for(let e=t[0],i=1;i<t.length;i++){let n=t[i];if(Ct(e,n)>0)return t.slice().sort(Ct);e=n}return t}(t):t)i.add(n.from,n.to,n.value);return i.finish()}static join(t){if(!t.length)return At.empty;let e=t[t.length-1];for(let i=t.length-2;i>=0;i--)for(let n=t[i];n!=At.empty;n=n.nextLayer)e=new At(n.chunkPos,n.chunk,e,Math.max(n.maxPoint,e.maxPoint));return e}}At.empty=new At([],[],null,-1),At.empty.nextLayer=At.empty;class Rt{finishChunk(t){this.chunks.push(new Tt(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,t&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(t,e,i){this.addInner(t,e,i)||(this.nextLayer||(this.nextLayer=new Rt)).add(t,e,i)}addInner(t,e,i){let n=t-this.lastTo||i.startSide-this.last.endSide;if(n<=0&&(t-this.lastFrom||i.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return!(n<0)&&(250==this.from.length&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=t),this.from.push(t-this.chunkStart),this.to.push(e-this.chunkStart),this.last=i,this.lastFrom=t,this.lastTo=e,this.value.push(i),i.point&&(this.maxPoint=Math.max(this.maxPoint,e-t)),!0)}addChunk(t,e){if((t-this.lastTo||e.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,e.maxPoint),this.chunks.push(e),this.chunkPos.push(t);let i=e.value.length-1;return this.last=e.value[i],this.lastFrom=e.from[i]+t,this.lastTo=e.to[i]+t,!0}finish(){return this.finishInner(At.empty)}finishInner(t){if(this.from.length&&this.finishChunk(!1),0==this.chunks.length)return t;let e=At.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(t):t,this.setMaxPoint);return this.from=null,e}}function Xt(t,e,i){let n=new Map;for(let e of t)for(let t=0;t<e.chunk.length;t++)e.chunk[t].maxPoint<=0&&n.set(e.chunk[t],e.chunkPos[t]);let s=new Set;for(let t of e)for(let e=0;e<t.chunk.length;e++){let r=n.get(t.chunk[e]);null==r||(i?i.mapPos(r):r)!=t.chunkPos[e]||(null==i?void 0:i.touchesRange(r,r+t.chunk[e].length))||s.add(t.chunk[e])}return s}class Yt{constructor(t,e,i,n=0){this.layer=t,this.skip=e,this.minPoint=i,this.rank=n}get startSide(){return this.value?this.value.startSide:0}get endSide(){return this.value?this.value.endSide:0}goto(t,e=-1e9){return this.chunkIndex=this.rangeIndex=0,this.gotoInner(t,e,!1),this}gotoInner(t,e,i){for(;this.chunkIndex<this.layer.chunk.length;){let e=this.layer.chunk[this.chunkIndex];if(!(this.skip&&this.skip.has(e)||this.layer.chunkEnd(this.chunkIndex)<t||e.maxPoint<this.minPoint))break;this.chunkIndex++,i=!1}if(this.chunkIndex<this.layer.chunk.length){let n=this.layer.chunk[this.chunkIndex].findIndex(t-this.layer.chunkPos[this.chunkIndex],e,!0);(!i||this.rangeIndex<n)&&this.setRangeIndex(n)}this.next()}forward(t,e){(this.to-t||this.endSide-e)<0&&this.gotoInner(t,e,!0)}next(){for(;;){if(this.chunkIndex==this.layer.chunk.length){this.from=this.to=1e9,this.value=null;break}{let t=this.layer.chunkPos[this.chunkIndex],e=this.layer.chunk[this.chunkIndex],i=t+e.from[this.rangeIndex];if(this.from=i,this.to=t+e.to[this.rangeIndex],this.value=e.value[this.rangeIndex],this.setRangeIndex(this.rangeIndex+1),this.minPoint<0||this.value.point&&this.to-this.from>=this.minPoint)break}}}setRangeIndex(t){if(t==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex<this.layer.chunk.length&&this.skip.has(this.layer.chunk[this.chunkIndex]);)this.chunkIndex++;this.rangeIndex=0}else this.rangeIndex=t}nextChunk(){this.chunkIndex++,this.rangeIndex=0,this.next()}compare(t){return this.from-t.from||this.startSide-t.startSide||this.rank-t.rank||this.to-t.to||this.endSide-t.endSide}}class Wt{constructor(t){this.heap=t}static from(t,e=null,i=-1){let n=[];for(let s=0;s<t.length;s++)for(let r=t[s];!r.isEmpty;r=r.nextLayer)r.maxPoint>=i&&n.push(new Yt(r,e,i,s));return 1==n.length?n[0]:new Wt(n)}get startSide(){return this.value?this.value.startSide:0}goto(t,e=-1e9){for(let i of this.heap)i.goto(t,e);for(let t=this.heap.length>>1;t>=0;t--)Mt(this.heap,t);return this.next(),this}forward(t,e){for(let i of this.heap)i.forward(t,e);for(let t=this.heap.length>>1;t>=0;t--)Mt(this.heap,t);(this.to-t||this.value.endSide-e)<0&&this.next()}next(){if(0==this.heap.length)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let t=this.heap[0];this.from=t.from,this.to=t.to,this.value=t.value,this.rank=t.rank,t.value&&t.next(),Mt(this.heap,0)}}}function Mt(t,e){for(let i=t[e];;){let n=1+(e<<1);if(n>=t.length)break;let s=t[n];if(n+1<t.length&&s.compare(t[n+1])>=0&&(s=t[n+1],n++),i.compare(s)<0)break;t[n]=i,t[e]=s,e=n}}class jt{constructor(t,e,i){this.minPoint=i,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=Wt.from(t,e,i)}goto(t,e=-1e9){return this.cursor.goto(t,e),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=t,this.endSide=e,this.openStart=-1,this.next(),this}forward(t,e){for(;this.minActive>-1&&(this.activeTo[this.minActive]-t||this.active[this.minActive].endSide-e)<0;)this.removeActive(this.minActive);this.cursor.forward(t,e)}removeActive(t){qt(this.active,t),qt(this.activeTo,t),qt(this.activeRank,t),this.minActive=Vt(this.active,this.activeTo)}addActive(t){let e=0,{value:i,to:n,rank:s}=this.cursor;for(;e<this.activeRank.length&&(s-this.activeRank[e]||n-this.activeTo[e])>0;)e++;_t(this.active,e,i),_t(this.activeTo,e,n),_t(this.activeRank,e,s),t&&_t(t,e,this.cursor.from),this.minActive=Vt(this.active,this.activeTo)}next(){let t=this.to,e=this.point;this.point=null;let i=this.openStart<0?[]:null;for(;;){let n=this.minActive;if(n>-1&&(this.activeTo[n]-this.cursor.from||this.active[n].endSide-this.cursor.startSide)<0){if(this.activeTo[n]>t){this.to=this.activeTo[n],this.endSide=this.active[n].endSide;break}this.removeActive(n),i&&qt(i,n)}else{if(!this.cursor.value){this.to=this.endSide=1e9;break}if(this.cursor.from>t){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}{let t=this.cursor.value;if(t.point){if(!(e&&this.cursor.to==this.to&&this.cursor.from<this.cursor.to)){this.point=t,this.pointFrom=this.cursor.from,this.pointRank=this.cursor.rank,this.to=this.cursor.to,this.endSide=t.endSide,this.cursor.next(),this.forward(this.to,this.endSide);break}this.cursor.next()}else this.addActive(i),this.cursor.next()}}}if(i){this.openStart=0;for(let e=i.length-1;e>=0&&i[e]<t;e--)this.openStart++}}activeForPoint(t){if(!this.active.length)return this.active;let e=[];for(let i=this.active.length-1;i>=0&&!(this.activeRank[i]<this.pointRank);i--)(this.activeTo[i]>t||this.activeTo[i]==t&&this.active[i].endSide>=this.point.endSide)&&e.push(this.active[i]);return e.reverse()}openEnd(t){let e=0;for(let i=this.activeTo.length-1;i>=0&&this.activeTo[i]>t;i--)e++;return e}}function Dt(t,e,i,n,s,r){t.goto(e),i.goto(n);let o=n+s,a=n,l=n-e;for(;;){let e=t.to+l-i.to||t.endSide-i.endSide,n=e<0?t.to+l:i.to,s=Math.min(n,o);if(t.point||i.point?t.point&&i.point&&(t.point==i.point||t.point.eq(i.point))&&Et(t.activeForPoint(t.to),i.activeForPoint(i.to))||r.comparePoint(a,s,t.point,i.point):s>a&&!Et(t.active,i.active)&&r.compareRange(a,s,t.active,i.active),n>o)break;a=n,e<=0&&t.next(),e>=0&&i.next()}}function Et(t,e){if(t.length!=e.length)return!1;for(let i=0;i<t.length;i++)if(t[i]!=e[i]&&!t[i].eq(e[i]))return!1;return!0}function qt(t,e){for(let i=e,n=t.length-1;i<n;i++)t[i]=t[i+1];t.pop()}function _t(t,e,i){for(let i=t.length-1;i>=e;i--)t[i+1]=t[i];t[e]=i}function Vt(t,e){let i=-1,n=1e9;for(let s=0;s<e.length;s++)(e[s]-n||t[s].endSide-t[i].endSide)<0&&(i=s,n=e[s]);return i}function It(t,e,i=t.length){let n=0;for(let s=0;s<i;)9==t.charCodeAt(s)?(n+=e-n%e,s++):(n++,s=O(t,s));return n}function zt(t,e,i,n){for(let n=0,s=0;;){if(s>=e)return n;if(n==t.length)break;s+=9==t.charCodeAt(n)?i-s%i:1,n=O(t,n)}return!0===n?-1:t.length}var Bt=Object.freeze({__proto__:null,Annotation:ct,AnnotationType:ft,ChangeDesc:Q,ChangeSet:$,get CharCategory(){return yt},Compartment:J,EditorSelection:Y,EditorState:Qt,Facet:j,Line:h,get MapMode(){return k},Prec:H,Range:Zt,RangeSet:At,RangeSetBuilder:Rt,RangeValue:Pt,SelectionRange:X,StateEffect:dt,StateEffectType:ut,StateField:z,Text:e,Transaction:pt,codePointAt:b,codePointSize:S,combineConfig:$t,countColumn:It,findClusterBreak:O,findColumn:zt,fromCodePoint:y});const Gt="undefined"==typeof Symbol?"__ͼ":Symbol.for("ͼ"),Lt="undefined"==typeof Symbol?"__styleSet"+Math.floor(1e8*Math.random()):Symbol("styleSet"),Nt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:{};class Ut{constructor(t,e){this.rules=[];let{finish:i}=e||{};function n(t){return/^@/.test(t)?[t]:t.split(/,\s*/)}function s(t,e,r,o){let a=[],l=/^@(\w+)\b/.exec(t[0]),h=l&&"keyframes"==l[1];if(l&&null==e)return r.push(t[0]+";");for(let i in e){let o=e[i];if(/&/.test(i))s(i.split(/,\s*/).map((e=>t.map((t=>e.replace(/&/,t))))).reduce(((t,e)=>t.concat(e))),o,r);else if(o&&"object"==typeof o){if(!l)throw new RangeError("The value of a property ("+i+") should be a primitive value.");s(n(i),o,a,h)}else null!=o&&a.push(i.replace(/_.*/,"").replace(/[A-Z]/g,(t=>"-"+t.toLowerCase()))+": "+o+";")}(a.length||h)&&r.push((!i||l||o?t:t.map(i)).join(", ")+" {"+a.join(" ")+"}")}for(let e in t)s(n(e),t[e],this.rules)}getRules(){return this.rules.join("\n")}static newName(){let t=Nt[Gt]||1;return Nt[Gt]=t+1,"ͼ"+t.toString(36)}static mount(t,e,i){let n=t[Lt],s=i&&i.nonce;n?s&&n.setNonce(s):n=new Ft(t,s),n.mount(Array.isArray(e)?e:[e])}}let Ht=new Map;class Ft{constructor(t,e){let i=t.ownerDocument||t,n=i.defaultView;if(!t.head&&t.adoptedStyleSheets&&n.CSSStyleSheet){let e=Ht.get(i);if(e)return t.adoptedStyleSheets=[e.sheet,...t.adoptedStyleSheets],t[Lt]=e;this.sheet=new n.CSSStyleSheet,t.adoptedStyleSheets=[this.sheet,...t.adoptedStyleSheets],Ht.set(i,this)}else{this.styleTag=i.createElement("style"),e&&this.styleTag.setAttribute("nonce",e);let n=t.head||t;n.insertBefore(this.styleTag,n.firstChild)}this.modules=[],t[Lt]=this}mount(t){let e=this.sheet,i=0,n=0;for(let s=0;s<t.length;s++){let r=t[s],o=this.modules.indexOf(r);if(o<n&&o>-1&&(this.modules.splice(o,1),n--,o=-1),-1==o){if(this.modules.splice(n++,0,r),e)for(let t=0;t<r.rules.length;t++)e.insertRule(r.rules[t],i++)}else{for(;n<o;)i+=this.modules[n++].rules.length;i+=r.rules.length,n++}}if(!e){let t="";for(let e=0;e<this.modules.length;e++)t+=this.modules[e].getRules()+"\n";this.styleTag.textContent=t}}setNonce(t){this.styleTag&&this.styleTag.getAttribute("nonce")!=t&&this.styleTag.setAttribute("nonce",t)}}for(var Jt={8:"Backspace",9:"Tab",10:"Enter",12:"NumLock",13:"Enter",16:"Shift",17:"Control",18:"Alt",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",44:"PrintScreen",45:"Insert",46:"Delete",59:";",61:"=",91:"Meta",92:"Meta",106:"*",107:"+",108:",",109:"-",110:".",111:"/",144:"NumLock",145:"ScrollLock",160:"Shift",161:"Shift",162:"Control",163:"Control",164:"Alt",165:"Alt",173:"-",186:";",187:"=",188:",",189:"-",190:".",191:"/",192:"`",219:"[",220:"\\",221:"]",222:"'"},Kt={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},te="undefined"!=typeof navigator&&/Mac/.test(navigator.platform),ee="undefined"!=typeof navigator&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),ie=0;ie<10;ie++)Jt[48+ie]=Jt[96+ie]=String(ie);for(ie=1;ie<=24;ie++)Jt[ie+111]="F"+ie;for(ie=65;ie<=90;ie++)Jt[ie]=String.fromCharCode(ie+32),Kt[ie]=String.fromCharCode(ie);for(var ne in Jt)Kt.hasOwnProperty(ne)||(Kt[ne]=Jt[ne]);function se(t){let e;return e=11==t.nodeType?t.getSelection?t:t.ownerDocument:t,e.getSelection()}function re(t,e){return!!e&&(t==e||t.contains(1!=e.nodeType?e.parentNode:e))}function oe(t,e){if(!e.anchorNode)return!1;try{return re(t,e.anchorNode)}catch(t){return!1}}function ae(t){return 3==t.nodeType?ve(t,0,t.nodeValue.length).getClientRects():1==t.nodeType?t.getClientRects():[]}function le(t,e,i,n){return!!i&&(ce(t,e,i,n,-1)||ce(t,e,i,n,1))}function he(t){for(var e=0;;e++)if(!(t=t.previousSibling))return e}function ce(t,e,i,n,s){for(;;){if(t==i&&e==n)return!0;if(e==(s<0?0:fe(t))){if("DIV"==t.nodeName)return!1;let i=t.parentNode;if(!i||1!=i.nodeType)return!1;e=he(t)+(s<0?0:1),t=i}else{if(1!=t.nodeType)return!1;if(1==(t=t.childNodes[e+(s<0?-1:0)]).nodeType&&"false"==t.contentEditable)return!1;e=s<0?fe(t):0}}}function fe(t){return 3==t.nodeType?t.nodeValue.length:t.childNodes.length}function ue(t,e){let i=e?t.left:t.right;return{left:i,right:i,top:t.top,bottom:t.bottom}}function de(t){return{left:0,right:t.innerWidth,top:0,bottom:t.innerHeight}}function pe(t,e){let i=e.width/t.offsetWidth,n=e.height/t.offsetHeight;return(i>.995&&i<1.005||!isFinite(i)||Math.abs(e.width-t.offsetWidth)<1)&&(i=1),(n>.995&&n<1.005||!isFinite(n)||Math.abs(e.height-t.offsetHeight)<1)&&(n=1),{scaleX:i,scaleY:n}}class Oe{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}eq(t){return this.anchorNode==t.anchorNode&&this.anchorOffset==t.anchorOffset&&this.focusNode==t.focusNode&&this.focusOffset==t.focusOffset}setRange(t){let{anchorNode:e,focusNode:i}=t;this.set(e,Math.min(t.anchorOffset,e?fe(e):0),i,Math.min(t.focusOffset,i?fe(i):0))}set(t,e,i,n){this.anchorNode=t,this.anchorOffset=e,this.focusNode=i,this.focusOffset=n}}let ge,me=null;function we(t){if(t.setActive)return t.setActive();if(me)return t.focus(me);let e=[];for(let i=t;i&&(e.push(i,i.scrollTop,i.scrollLeft),i!=i.ownerDocument);i=i.parentNode);if(t.focus(null==me?{get preventScroll(){return me={preventScroll:!0},!0}}:void 0),!me){me=!1;for(let t=0;t<e.length;){let i=e[t++],n=e[t++],s=e[t++];i.scrollTop!=n&&(i.scrollTop=n),i.scrollLeft!=s&&(i.scrollLeft=s)}}}function ve(t,e,i=e){let n=ge||(ge=document.createRange());return n.setEnd(t,i),n.setStart(t,e),n}function be(t,e,i){let n={key:e,code:e,keyCode:i,which:i,cancelable:!0},s=new KeyboardEvent("keydown",n);s.synthetic=!0,t.dispatchEvent(s);let r=new KeyboardEvent("keyup",n);return r.synthetic=!0,t.dispatchEvent(r),s.defaultPrevented||r.defaultPrevented}function ye(t){for(;t.attributes.length;)t.removeAttributeNode(t.attributes[0])}function Se(t){return t.scrollTop>Math.max(1,t.scrollHeight-t.clientHeight-4)}class xe{constructor(t,e,i=!0){this.node=t,this.offset=e,this.precise=i}static before(t,e){return new xe(t.parentNode,he(t),e)}static after(t,e){return new xe(t.parentNode,he(t)+1,e)}}const ke=[];class Qe{constructor(){this.parent=null,this.dom=null,this.flags=2}get overrideDOMText(){return null}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(t){let e=this.posAtStart;for(let i of this.children){if(i==t)return e;e+=i.length+i.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(t){return this.posBefore(t)+t.length}sync(t,e){if(2&this.flags){let i,n=this.dom,s=null;for(let r of this.children){if(7&r.flags){if(!r.dom&&(i=s?s.nextSibling:n.firstChild)){let t=Qe.get(i);(!t||!t.parent&&t.canReuseDOM(r))&&r.reuseDOM(i)}r.sync(t,e),r.flags&=-8}if(i=s?s.nextSibling:n.firstChild,e&&!e.written&&e.node==n&&i!=r.dom&&(e.written=!0),r.dom.parentNode==n)for(;i&&i!=r.dom;)i=$e(i);else n.insertBefore(r.dom,i);s=r.dom}for(i=s?s.nextSibling:n.firstChild,i&&e&&e.node==n&&(e.written=!0);i;)i=$e(i)}else if(1&this.flags)for(let i of this.children)7&i.flags&&(i.sync(t,e),i.flags&=-8)}reuseDOM(t){}localPosFromDOM(t,e){let i;if(t==this.dom)i=this.dom.childNodes[e];else{let n=0==fe(t)?0:0==e?-1:1;for(;;){let e=t.parentNode;if(e==this.dom)break;0==n&&e.firstChild!=e.lastChild&&(n=t==e.firstChild?-1:1),t=e}i=n<0?t:t.nextSibling}if(i==this.dom.firstChild)return 0;for(;i&&!Qe.get(i);)i=i.nextSibling;if(!i)return this.length;for(let t=0,e=0;;t++){let n=this.children[t];if(n.dom==i)return e;e+=n.length+n.breakAfter}}domBoundsAround(t,e,i=0){let n=-1,s=-1,r=-1,o=-1;for(let a=0,l=i,h=i;a<this.children.length;a++){let i=this.children[a],c=l+i.length;if(l<t&&c>e)return i.domBoundsAround(t,e,l);if(c>=t&&-1==n&&(n=a,s=l),l>e&&i.dom.parentNode==this.dom){r=a,o=h;break}h=c,l=c+i.breakAfter}return{from:s,to:o<0?i+this.length:o,startDOM:(n?this.children[n-1].dom.nextSibling:null)||this.dom.firstChild,endDOM:r<this.children.length&&r>=0?this.children[r].dom:null}}markDirty(t=!1){this.flags|=2,this.markParentsDirty(t)}markParentsDirty(t){for(let e=this.parent;e;e=e.parent){if(t&&(e.flags|=2),1&e.flags)return;e.flags|=1,t=!1}}setParent(t){this.parent!=t&&(this.parent=t,7&this.flags&&this.markParentsDirty(!0))}setDOM(t){this.dom!=t&&(this.dom&&(this.dom.cmView=null),this.dom=t,t.cmView=this)}get rootView(){for(let t=this;;){let e=t.parent;if(!e)return t;t=e}}replaceChildren(t,e,i=ke){this.markDirty();for(let n=t;n<e;n++){let t=this.children[n];t.parent==this&&i.indexOf(t)<0&&t.destroy()}this.children.splice(t,e-t,...i);for(let t=0;t<i.length;t++)i[t].setParent(this)}ignoreMutation(t){return!1}ignoreEvent(t){return!1}childCursor(t=this.length){return new Pe(this.children,t,this.children.length)}childPos(t,e=1){return this.childCursor().findPos(t,e)}toString(){let t=this.constructor.name.replace("View","");return t+(this.children.length?"("+this.children.join()+")":this.length?"["+("Text"==t?this.text:this.length)+"]":"")+(this.breakAfter?"#":"")}static get(t){return t.cmView}get isEditable(){return!0}get isWidget(){return!1}get isHidden(){return!1}merge(t,e,i,n,s,r){return!1}become(t){return!1}canReuseDOM(t){return t.constructor==this.constructor&&!(8&(this.flags|t.flags))}getSide(){return 0}destroy(){for(let t of this.children)t.parent==this&&t.destroy();this.parent=null}}function $e(t){let e=t.nextSibling;return t.parentNode.removeChild(t),e}Qe.prototype.breakAfter=0;class Pe{constructor(t,e,i){this.children=t,this.pos=e,this.i=i,this.off=0}findPos(t,e=1){for(;;){if(t>this.pos||t==this.pos&&(e>0||0==this.i||this.children[this.i-1].breakAfter))return this.off=t-this.pos,this;let i=this.children[--this.i];this.pos-=i.length+i.breakAfter}}}function Ze(t,e,i,n,s,r,o,a,l){let{children:h}=t,c=h.length?h[e]:null,f=r.length?r[r.length-1]:null,u=f?f.breakAfter:o;if(!(e==n&&c&&!o&&!u&&r.length<2&&c.merge(i,s,r.length?f:null,0==i,a,l))){if(n<h.length){let t=h[n];t&&(s<t.length||t.breakAfter&&(null==f?void 0:f.breakAfter))?(e==n&&(t=t.split(s),s=0),!u&&f&&t.merge(0,s,f,!0,0,l)?r[r.length-1]=t:((s||t.children.length&&!t.children[0].length)&&t.merge(0,s,null,!1,0,l),r.push(t))):(null==t?void 0:t.breakAfter)&&(f?f.breakAfter=1:o=1),n++}for(c&&(c.breakAfter=o,i>0&&(!o&&r.length&&c.merge(i,c.length,r[0],!1,a,0)?c.breakAfter=r.shift().breakAfter:(i<c.length||c.children.length&&0==c.children[c.children.length-1].length)&&c.merge(i,c.length,null,!1,a,0),e++));e<n&&r.length;)if(h[n-1].become(r[r.length-1]))n--,r.pop(),l=r.length?0:a;else{if(!h[e].become(r[0]))break;e++,r.shift(),a=r.length?0:l}!r.length&&e&&n<h.length&&!h[e-1].breakAfter&&h[n].merge(0,0,h[e-1],!1,a,l)&&e--,(e<n||r.length)&&t.replaceChildren(e,n,r)}}function Ce(t,e,i,n,s,r){let o=t.childCursor(),{i:a,off:l}=o.findPos(i,1),{i:h,off:c}=o.findPos(e,-1),f=e-i;for(let t of n)f+=t.length;t.length+=f,Ze(t,h,c,a,l,n,0,s,r)}let Te="undefined"!=typeof navigator?navigator:{userAgent:"",vendor:"",platform:""},Ae="undefined"!=typeof document?document:{documentElement:{style:{}}};const Re=/Edge\/(\d+)/.exec(Te.userAgent),Xe=/MSIE \d/.test(Te.userAgent),Ye=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(Te.userAgent),We=!!(Xe||Ye||Re),Me=!We&&/gecko\/(\d+)/i.test(Te.userAgent),je=!We&&/Chrome\/(\d+)/.exec(Te.userAgent),De="webkitFontSmoothing"in Ae.documentElement.style,Ee=!We&&/Apple Computer/.test(Te.vendor),qe=Ee&&(/Mobile\/\w+/.test(Te.userAgent)||Te.maxTouchPoints>2);var _e={mac:qe||/Mac/.test(Te.platform),windows:/Win/.test(Te.platform),linux:/Linux|X11/.test(Te.platform),ie:We,ie_version:Xe?Ae.documentMode||6:Ye?+Ye[1]:Re?+Re[1]:0,gecko:Me,gecko_version:Me?+(/Firefox\/(\d+)/.exec(Te.userAgent)||[0,0])[1]:0,chrome:!!je,chrome_version:je?+je[1]:0,ios:qe,android:/Android\b/.test(Te.userAgent),webkit:De,safari:Ee,webkit_version:De?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0,tabSize:null!=Ae.documentElement.style.tabSize?"tab-size":"-moz-tab-size"};class Ve extends Qe{constructor(t){super(),this.text=t}get length(){return this.text.length}createDOM(t){this.setDOM(t||document.createTextNode(this.text))}sync(t,e){this.dom||this.createDOM(),this.dom.nodeValue!=this.text&&(e&&e.node==this.dom&&(e.written=!0),this.dom.nodeValue=this.text)}reuseDOM(t){3==t.nodeType&&this.createDOM(t)}merge(t,e,i){return!(8&this.flags||i&&(!(i instanceof Ve)||this.length-(e-t)+i.length>256||8&i.flags))&&(this.text=this.text.slice(0,t)+(i?i.text:"")+this.text.slice(e),this.markDirty(),!0)}split(t){let e=new Ve(this.text.slice(t));return this.text=this.text.slice(0,t),this.markDirty(),e.flags|=8&this.flags,e}localPosFromDOM(t,e){return t==this.dom?e:e?this.text.length:0}domAtPos(t){return new xe(this.dom,t)}domBoundsAround(t,e,i){return{from:i,to:i+this.length,startDOM:this.dom,endDOM:this.dom.nextSibling}}coordsAt(t,e){return function(t,e,i){let n=t.nodeValue.length;e>n&&(e=n);let s=e,r=e,o=0;0==e&&i<0||e==n&&i>=0?_e.chrome||_e.gecko||(e?(s--,o=1):r<n&&(r++,o=-1)):i<0?s--:r<n&&r++;let a=ve(t,s,r).getClientRects();if(!a.length)return null;let l=a[(o?o<0:i>=0)?0:a.length-1];_e.safari&&!o&&0==l.width&&(l=Array.prototype.find.call(a,(t=>t.width))||l);return o?ue(l,o<0):l||null}(this.dom,t,e)}}class Ie extends Qe{constructor(t,e=[],i=0){super(),this.mark=t,this.children=e,this.length=i;for(let t of e)t.setParent(this)}setAttrs(t){if(ye(t),this.mark.class&&(t.className=this.mark.class),this.mark.attrs)for(let e in this.mark.attrs)t.setAttribute(e,this.mark.attrs[e]);return t}canReuseDOM(t){return super.canReuseDOM(t)&&!(8&(this.flags|t.flags))}reuseDOM(t){t.nodeName==this.mark.tagName.toUpperCase()&&(this.setDOM(t),this.flags|=6)}sync(t,e){this.dom?4&this.flags&&this.setAttrs(this.dom):this.setDOM(this.setAttrs(document.createElement(this.mark.tagName))),super.sync(t,e)}merge(t,e,i,n,s,r){return(!i||!(!(i instanceof Ie&&i.mark.eq(this.mark))||t&&s<=0||e<this.length&&r<=0))&&(Ce(this,t,e,i?i.children.slice():[],s-1,r-1),this.markDirty(),!0)}split(t){let e=[],i=0,n=-1,s=0;for(let r of this.children){let o=i+r.length;o>t&&e.push(i<t?r.split(t-i):r),n<0&&i>=t&&(n=s),i=o,s++}let r=this.length-t;return this.length=t,n>-1&&(this.children.length=n,this.markDirty()),new Ie(this.mark,e,r)}domAtPos(t){return Ge(this,t)}coordsAt(t,e){return Ne(this,t,e)}}class ze extends Qe{static create(t,e,i){return new ze(t,e,i)}constructor(t,e,i){super(),this.widget=t,this.length=e,this.side=i,this.prevWidget=null}split(t){let e=ze.create(this.widget,this.length-t,this.side);return this.length-=t,e}sync(t){this.dom&&this.widget.updateDOM(this.dom,t)||(this.dom&&this.prevWidget&&this.prevWidget.destroy(this.dom),this.prevWidget=null,this.setDOM(this.widget.toDOM(t)),this.widget.editable||(this.dom.contentEditable="false"))}getSide(){return this.side}merge(t,e,i,n,s,r){return!(i&&(!(i instanceof ze&&this.widget.compare(i.widget))||t>0&&s<=0||e<this.length&&r<=0))&&(this.length=t+(i?i.length:0)+(this.length-e),!0)}become(t){return t instanceof ze&&t.side==this.side&&this.widget.constructor==t.widget.constructor&&(this.widget.compare(t.widget)||this.markDirty(!0),this.dom&&!this.prevWidget&&(this.prevWidget=this.widget),this.widget=t.widget,this.length=t.length,!0)}ignoreMutation(){return!0}ignoreEvent(t){return this.widget.ignoreEvent(t)}get overrideDOMText(){if(0==this.length)return e.empty;let t=this;for(;t.parent;)t=t.parent;let{view:i}=t,n=i&&i.state.doc,s=this.posAtStart;return n?n.slice(s,s+this.length):e.empty}domAtPos(t){return(this.length?0==t:this.side>0)?xe.before(this.dom):xe.after(this.dom,t==this.length)}domBoundsAround(){return null}coordsAt(t,e){let i=this.widget.coordsAt(this.dom,t,e);if(i)return i;let n=this.dom.getClientRects(),s=null;if(!n.length)return null;let r=this.side?this.side<0:t>0;for(let e=r?n.length-1:0;s=n[e],!(t>0?0==e:e==n.length-1||s.top<s.bottom);e+=r?-1:1);return ue(s,!r)}get isEditable(){return!1}get isWidget(){return!0}get isHidden(){return this.widget.isHidden}destroy(){super.destroy(),this.dom&&this.widget.destroy(this.dom)}}class Be extends Qe{constructor(t){super(),this.side=t}get length(){return 0}merge(){return!1}become(t){return t instanceof Be&&t.side==this.side}split(){return new Be(this.side)}sync(){if(!this.dom){let t=document.createElement("img");t.className="cm-widgetBuffer",t.setAttribute("aria-hidden","true"),this.setDOM(t)}}getSide(){return this.side}domAtPos(t){return this.side>0?xe.before(this.dom):xe.after(this.dom)}localPosFromDOM(){return 0}domBoundsAround(){return null}coordsAt(t){return this.dom.getBoundingClientRect()}get overrideDOMText(){return e.empty}get isHidden(){return!0}}function Ge(t,e){let i=t.dom,{children:n}=t,s=0;for(let t=0;s<n.length;s++){let r=n[s],o=t+r.length;if(!(o==t&&r.getSide()<=0)){if(e>t&&e<o&&r.dom.parentNode==i)return r.domAtPos(e-t);if(e<=t)break;t=o}}for(let t=s;t>0;t--){let e=n[t-1];if(e.dom.parentNode==i)return e.domAtPos(e.length)}for(let t=s;t<n.length;t++){let e=n[t];if(e.dom.parentNode==i)return e.domAtPos(0)}return new xe(i,0)}function Le(t,e,i){let n,{children:s}=t;i>0&&e instanceof Ie&&s.length&&(n=s[s.length-1])instanceof Ie&&n.mark.eq(e.mark)?Le(n,e.children[0],i-1):(s.push(e),e.setParent(t)),t.length+=e.length}function Ne(t,e,i){let n=null,s=-1,r=null,o=-1;!function t(e,a){for(let l=0,h=0;l<e.children.length&&h<=a;l++){let c=e.children[l],f=h+c.length;f>=a&&(c.children.length?t(c,a-h):(!r||r.isHidden&&i>0)&&(f>a||h==f&&c.getSide()>0)?(r=c,o=a-h):(h<a||h==f&&c.getSide()<0&&!c.isHidden)&&(n=c,s=a-h)),h=f}}(t,e);let a=(i<0?n:r)||n||r;return a?a.coordsAt(Math.max(0,a==n?s:o),i):function(t){let e=t.dom.lastChild;if(!e)return t.dom.getBoundingClientRect();let i=ae(e);return i[i.length-1]||null}(t)}function Ue(t,e){for(let i in t)"class"==i&&e.class?e.class+=" "+t.class:"style"==i&&e.style?e.style+=";"+t.style:e[i]=t[i];return e}Ve.prototype.children=ze.prototype.children=Be.prototype.children=ke;const He=Object.create(null);function Fe(t,e,i){if(t==e)return!0;t||(t=He),e||(e=He);let n=Object.keys(t),s=Object.keys(e);if(n.length-(i&&n.indexOf(i)>-1?1:0)!=s.length-(i&&s.indexOf(i)>-1?1:0))return!1;for(let r of n)if(r!=i&&(-1==s.indexOf(r)||t[r]!==e[r]))return!1;return!0}function Je(t,e,i){let n=!1;if(e)for(let s in e)i&&s in i||(n=!0,"style"==s?t.style.cssText="":t.removeAttribute(s));if(i)for(let s in i)e&&e[s]==i[s]||(n=!0,"style"==s?t.style.cssText=i[s]:t.setAttribute(s,i[s]));return n}function Ke(t){let e=Object.create(null);for(let i=0;i<t.attributes.length;i++){let n=t.attributes[i];e[n.name]=n.value}return e}class ti extends Qe{constructor(){super(...arguments),this.children=[],this.length=0,this.prevAttrs=void 0,this.attrs=null,this.breakAfter=0}merge(t,e,i,n,s,r){if(i){if(!(i instanceof ti))return!1;this.dom||i.transferDOM(this)}return n&&this.setDeco(i?i.attrs:null),Ce(this,t,e,i?i.children.slice():[],s,r),!0}split(t){let e=new ti;if(e.breakAfter=this.breakAfter,0==this.length)return e;let{i:i,off:n}=this.childPos(t);n&&(e.append(this.children[i].split(n),0),this.children[i].merge(n,this.children[i].length,null,!1,0,0),i++);for(let t=i;t<this.children.length;t++)e.append(this.children[t],0);for(;i>0&&0==this.children[i-1].length;)this.children[--i].destroy();return this.children.length=i,this.markDirty(),this.length=t,e}transferDOM(t){this.dom&&(this.markDirty(),t.setDOM(this.dom),t.prevAttrs=void 0===this.prevAttrs?this.attrs:this.prevAttrs,this.prevAttrs=void 0,this.dom=null)}setDeco(t){Fe(this.attrs,t)||(this.dom&&(this.prevAttrs=this.attrs,this.markDirty()),this.attrs=t)}append(t,e){Le(this,t,e)}addLineDeco(t){let e=t.spec.attributes,i=t.spec.class;e&&(this.attrs=Ue(e,this.attrs||{})),i&&(this.attrs=Ue({class:i},this.attrs||{}))}domAtPos(t){return Ge(this,t)}reuseDOM(t){"DIV"==t.nodeName&&(this.setDOM(t),this.flags|=6)}sync(t,e){var i;this.dom?4&this.flags&&(ye(this.dom),this.dom.className="cm-line",this.prevAttrs=this.attrs?null:void 0):(this.setDOM(document.createElement("div")),this.dom.className="cm-line",this.prevAttrs=this.attrs?null:void 0),void 0!==this.prevAttrs&&(Je(this.dom,this.prevAttrs,this.attrs),this.dom.classList.add("cm-line"),this.prevAttrs=void 0),super.sync(t,e);let n=this.dom.lastChild;for(;n&&Qe.get(n)instanceof Ie;)n=n.lastChild;if(!(n&&this.length&&("BR"==n.nodeName||0!=(null===(i=Qe.get(n))||void 0===i?void 0:i.isEditable)||_e.ios&&this.children.some((t=>t instanceof Ve))))){let t=document.createElement("BR");t.cmIgnore=!0,this.dom.appendChild(t)}}measureTextSize(){if(0==this.children.length||this.length>20)return null;let t,e=0;for(let i of this.children){if(!(i instanceof Ve)||/[^ -~]/.test(i.text))return null;let n=ae(i.dom);if(1!=n.length)return null;e+=n[0].width,t=n[0].height}return e?{lineHeight:this.dom.getBoundingClientRect().height,charWidth:e/this.length,textHeight:t}:null}coordsAt(t,e){let i=Ne(this,t,e);if(!this.children.length&&i&&this.parent){let{heightOracle:t}=this.parent.view.viewState,e=i.bottom-i.top;if(Math.abs(e-t.lineHeight)<2&&t.textHeight<e){let n=(e-t.textHeight)/2;return{top:i.top+n,bottom:i.bottom-n,left:i.left,right:i.left}}}return i}become(t){return!1}covers(){return!0}static find(t,e){for(let i=0,n=0;i<t.children.length;i++){let s=t.children[i],r=n+s.length;if(r>=e){if(s instanceof ti)return s;if(r>e)break}n=r+s.breakAfter}return null}}class ei extends Qe{constructor(t,e,i){super(),this.widget=t,this.length=e,this.deco=i,this.breakAfter=0,this.prevWidget=null}merge(t,e,i,n,s,r){return!(i&&(!(i instanceof ei&&this.widget.compare(i.widget))||t>0&&s<=0||e<this.length&&r<=0))&&(this.length=t+(i?i.length:0)+(this.length-e),!0)}domAtPos(t){return 0==t?xe.before(this.dom):xe.after(this.dom,t==this.length)}split(t){let e=this.length-t;this.length=t;let i=new ei(this.widget,e,this.deco);return i.breakAfter=this.breakAfter,i}get children(){return ke}sync(t){this.dom&&this.widget.updateDOM(this.dom,t)||(this.dom&&this.prevWidget&&this.prevWidget.destroy(this.dom),this.prevWidget=null,this.setDOM(this.widget.toDOM(t)),this.widget.editable||(this.dom.contentEditable="false"))}get overrideDOMText(){return this.parent?this.parent.view.state.doc.slice(this.posAtStart,this.posAtEnd):e.empty}domBoundsAround(){return null}become(t){return t instanceof ei&&t.widget.constructor==this.widget.constructor&&(t.widget.compare(this.widget)||this.markDirty(!0),this.dom&&!this.prevWidget&&(this.prevWidget=this.widget),this.widget=t.widget,this.length=t.length,this.deco=t.deco,this.breakAfter=t.breakAfter,!0)}ignoreMutation(){return!0}ignoreEvent(t){return this.widget.ignoreEvent(t)}get isEditable(){return!1}get isWidget(){return!0}coordsAt(t,e){return this.widget.coordsAt(this.dom,t,e)}destroy(){super.destroy(),this.dom&&this.widget.destroy(this.dom)}covers(t){let{startSide:e,endSide:i}=this.deco;return e!=i&&(t<0?e<0:i>0)}}class ii{eq(t){return!1}updateDOM(t,e){return!1}compare(t){return this==t||this.constructor==t.constructor&&this.eq(t)}get estimatedHeight(){return-1}get lineBreaks(){return 0}ignoreEvent(t){return!0}coordsAt(t,e,i){return null}get isHidden(){return!1}get editable(){return!1}destroy(t){}}var ni=function(t){return t[t.Text=0]="Text",t[t.WidgetBefore=1]="WidgetBefore",t[t.WidgetAfter=2]="WidgetAfter",t[t.WidgetRange=3]="WidgetRange",t}(ni||(ni={}));class si extends Pt{constructor(t,e,i,n){super(),this.startSide=t,this.endSide=e,this.widget=i,this.spec=n}get heightRelevant(){return!1}static mark(t){return new ri(t)}static widget(t){let e=Math.max(-1e4,Math.min(1e4,t.side||0)),i=!!t.block;return e+=i&&!t.inlineOrder?e>0?3e8:-4e8:e>0?1e8:-1e8,new ai(t,e,e,i,t.widget||null,!1)}static replace(t){let e,i,n=!!t.block;if(t.isBlockGap)e=-5e8,i=4e8;else{let{start:s,end:r}=li(t,n);e=(s?n?-3e8:-1:5e8)-1,i=1+(r?n?2e8:1:-6e8)}return new ai(t,e,i,n,t.widget||null,!0)}static line(t){return new oi(t)}static set(t,e=!1){return At.of(t,e)}hasHeight(){return!!this.widget&&this.widget.estimatedHeight>-1}}si.none=At.empty;class ri extends si{constructor(t){let{start:e,end:i}=li(t);super(e?-1:5e8,i?1:-6e8,null,t),this.tagName=t.tagName||"span",this.class=t.class||"",this.attrs=t.attributes||null}eq(t){var e,i;return this==t||t instanceof ri&&this.tagName==t.tagName&&(this.class||(null===(e=this.attrs)||void 0===e?void 0:e.class))==(t.class||(null===(i=t.attrs)||void 0===i?void 0:i.class))&&Fe(this.attrs,t.attrs,"class")}range(t,e=t){if(t>=e)throw new RangeError("Mark decorations may not be empty");return super.range(t,e)}}ri.prototype.point=!1;class oi extends si{constructor(t){super(-2e8,-2e8,null,t)}eq(t){return t instanceof oi&&this.spec.class==t.spec.class&&Fe(this.spec.attributes,t.spec.attributes)}range(t,e=t){if(e!=t)throw new RangeError("Line decoration ranges must be zero-length");return super.range(t,e)}}oi.prototype.mapMode=k.TrackBefore,oi.prototype.point=!0;class ai extends si{constructor(t,e,i,n,s,r){super(e,i,s,t),this.block=n,this.isReplace=r,this.mapMode=n?e<=0?k.TrackBefore:k.TrackAfter:k.TrackDel}get type(){return this.startSide!=this.endSide?ni.WidgetRange:this.startSide<=0?ni.WidgetBefore:ni.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(t){return t instanceof ai&&(e=this.widget,i=t.widget,e==i||!!(e&&i&&e.compare(i)))&&this.block==t.block&&this.startSide==t.startSide&&this.endSide==t.endSide;var e,i}range(t,e=t){if(this.isReplace&&(t>e||t==e&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&e!=t)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(t,e)}}function li(t,e=!1){let{inclusiveStart:i,inclusiveEnd:n}=t;return null==i&&(i=t.inclusive),null==n&&(n=t.inclusive),{start:null!=i?i:e,end:null!=n?n:e}}function hi(t,e,i,n=0){let s=i.length-1;s>=0&&i[s]+n>=t?i[s]=Math.max(i[s],e):i.push(t,e)}ai.prototype.point=!0;class ci{constructor(t,e,i,n){this.doc=t,this.pos=e,this.end=i,this.disallowBlockEffectsFor=n,this.content=[],this.curLine=null,this.breakAtStart=0,this.pendingBuffer=0,this.bufferMarks=[],this.atCursorPos=!0,this.openStart=-1,this.openEnd=-1,this.text="",this.textOff=0,this.cursor=t.iter(),this.skip=e}posCovered(){if(0==this.content.length)return!this.breakAtStart&&this.doc.lineAt(this.pos).from!=this.pos;let t=this.content[this.content.length-1];return!(t.breakAfter||t instanceof ei&&t.deco.endSide<0)}getLine(){return this.curLine||(this.content.push(this.curLine=new ti),this.atCursorPos=!0),this.curLine}flushBuffer(t=this.bufferMarks){this.pendingBuffer&&(this.curLine.append(fi(new Be(-1),t),t.length),this.pendingBuffer=0)}addBlockWidget(t){this.flushBuffer(),this.curLine=null,this.content.push(t)}finish(t){this.pendingBuffer&&t<=this.bufferMarks.length?this.flushBuffer():this.pendingBuffer=0,this.posCovered()||t&&this.content.length&&this.content[this.content.length-1]instanceof ei||this.getLine()}buildText(t,e,i){for(;t>0;){if(this.textOff==this.text.length){let{value:e,lineBreak:i,done:n}=this.cursor.next(this.skip);if(this.skip=0,n)throw new Error("Ran out of text content when drawing inline views");if(i){this.posCovered()||this.getLine(),this.content.length?this.content[this.content.length-1].breakAfter=1:this.breakAtStart=1,this.flushBuffer(),this.curLine=null,this.atCursorPos=!0,t--;continue}this.text=e,this.textOff=0}let n=Math.min(this.text.length-this.textOff,t,512);this.flushBuffer(e.slice(e.length-i)),this.getLine().append(fi(new Ve(this.text.slice(this.textOff,this.textOff+n)),e),i),this.atCursorPos=!0,this.textOff+=n,t-=n,i=0}}span(t,e,i,n){this.buildText(e-t,i,n),this.pos=e,this.openStart<0&&(this.openStart=n)}point(t,e,i,n,s,r){if(this.disallowBlockEffectsFor[r]&&i instanceof ai){if(i.block)throw new RangeError("Block decorations may not be specified via plugins");if(e>this.doc.lineAt(this.pos).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}let o=e-t;if(i instanceof ai)if(i.block)i.startSide>0&&!this.posCovered()&&this.getLine(),this.addBlockWidget(new ei(i.widget||new ui("div"),o,i));else{let r=ze.create(i.widget||new ui("span"),o,o?0:i.startSide),a=this.atCursorPos&&!r.isEditable&&s<=n.length&&(t<e||i.startSide>0),l=!r.isEditable&&(t<e||s>n.length||i.startSide<=0),h=this.getLine();2!=this.pendingBuffer||a||r.isEditable||(this.pendingBuffer=0),this.flushBuffer(n),a&&(h.append(fi(new Be(1),n),s),s=n.length+Math.max(0,s-n.length)),h.append(fi(r,n),s),this.atCursorPos=l,this.pendingBuffer=l?t<e||s>n.length?1:2:0,this.pendingBuffer&&(this.bufferMarks=n.slice())}else this.doc.lineAt(this.pos).from==this.pos&&this.getLine().addLineDeco(i);o&&(this.textOff+o<=this.text.length?this.textOff+=o:(this.skip+=o-(this.text.length-this.textOff),this.text="",this.textOff=0),this.pos=e),this.openStart<0&&(this.openStart=s)}static build(t,e,i,n,s){let r=new ci(t,e,i,s);return r.openEnd=At.spans(n,e,i,r),r.openStart<0&&(r.openStart=r.openEnd),r.finish(r.openEnd),r}}function fi(t,e){for(let i of e)t=new Ie(i,[t],t.length);return t}class ui extends ii{constructor(t){super(),this.tag=t}eq(t){return t.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(t){return t.nodeName.toLowerCase()==this.tag}get isHidden(){return!0}}var di=function(t){return t[t.LTR=0]="LTR",t[t.RTL=1]="RTL",t}(di||(di={}));const pi=di.LTR,Oi=di.RTL;function gi(t){let e=[];for(let i=0;i<t.length;i++)e.push(1<<+t[i]);return e}const mi=gi("88888888888888888888888888888888888666888888787833333333337888888000000000000000000000000008888880000000000000000000000000088888888888888888888888888888888888887866668888088888663380888308888800000000000000000000000800000000000000000000000000000008"),wi=gi("4444448826627288999999999992222222222222222222222222222222222222222222222229999999999999999999994444444444644222822222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222222999999949999999229989999223333333333"),vi=Object.create(null),bi=[];for(let t of["()","[]","{}"]){let e=t.charCodeAt(0),i=t.charCodeAt(1);vi[e]=i,vi[i]=-e}function yi(t){return t<=247?mi[t]:1424<=t&&t<=1524?2:1536<=t&&t<=1785?wi[t-1536]:1774<=t&&t<=2220?4:8192<=t&&t<=8204?256:64336<=t&&t<=65023?4:1}const Si=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/;class xi{get dir(){return this.level%2?Oi:pi}constructor(t,e,i){this.from=t,this.to=e,this.level=i}side(t,e){return this.dir==e==t?this.to:this.from}forward(t,e){return t==(this.dir==e)}static find(t,e,i,n){let s=-1;for(let r=0;r<t.length;r++){let o=t[r];if(o.from<=e&&o.to>=e){if(o.level==i)return r;(s<0||(0!=n?n<0?o.from<e:o.to>e:t[s].level>o.level))&&(s=r)}}if(s<0)throw new RangeError("Index out of range");return s}}function ki(t,e){if(t.length!=e.length)return!1;for(let i=0;i<t.length;i++){let n=t[i],s=e[i];if(n.from!=s.from||n.to!=s.to||n.direction!=s.direction||!ki(n.inner,s.inner))return!1}return!0}const Qi=[];function $i(t,e,i,n,s,r,o){let a=n%2?2:1;if(n%2==s%2)for(let l=e,h=0;l<i;){let e=!0,c=!1;if(h==r.length||l<r[h].from){let t=Qi[l];t!=a&&(e=!1,c=16==t)}let f=e||1!=a?null:[],u=e?n:n+1,d=l;t:for(;;)if(h<r.length&&d==r[h].from){if(c)break t;let p=r[h];if(!e)for(let t=p.to,e=h+1;;){if(t==i)break t;if(!(e<r.length&&r[e].from==t)){if(Qi[t]==a)break t;break}t=r[e++].to}if(h++,f)f.push(p);else{p.from>l&&o.push(new xi(l,p.from,u)),Pi(t,p.direction==pi!=!(u%2)?n+1:n,s,p.inner,p.from,p.to,o),l=p.to}d=p.to}else{if(d==i||(e?Qi[d]!=a:Qi[d]==a))break;d++}f?$i(t,l,d,n+1,s,f,o):l<d&&o.push(new xi(l,d,u)),l=d}else for(let l=i,h=r.length;l>e;){let i=!0,c=!1;if(!h||l>r[h-1].to){let t=Qi[l-1];t!=a&&(i=!1,c=16==t)}let f=i||1!=a?null:[],u=i?n:n+1,d=l;t:for(;;)if(h&&d==r[h-1].to){if(c)break t;let p=r[--h];if(!i)for(let t=p.from,i=h;;){if(t==e)break t;if(!i||r[i-1].to!=t){if(Qi[t-1]==a)break t;break}t=r[--i].from}if(f)f.push(p);else{p.to<l&&o.push(new xi(p.to,l,u)),Pi(t,p.direction==pi!=!(u%2)?n+1:n,s,p.inner,p.from,p.to,o),l=p.from}d=p.from}else{if(d==e||(i?Qi[d-1]!=a:Qi[d-1]==a))break;d--}f?$i(t,d,l,n+1,s,f,o):d<l&&o.push(new xi(d,l,u)),l=d}}function Pi(t,e,i,n,s,r,o){let a=e%2?2:1;!function(t,e,i,n,s){for(let r=0;r<=n.length;r++){let o=r?n[r-1].to:e,a=r<n.length?n[r].from:i,l=r?256:s;for(let e=o,i=l,n=l;e<a;e++){let s=yi(t.charCodeAt(e));512==s?s=i:8==s&&4==n&&(s=16),Qi[e]=4==s?2:s,7&s&&(n=s),i=s}for(let t=o,e=l,n=l;t<a;t++){let s=Qi[t];if(128==s)t<a-1&&e==Qi[t+1]&&24&e?s=Qi[t]=e:Qi[t]=256;else if(64==s){let s=t+1;for(;s<a&&64==Qi[s];)s++;let r=t&&8==e||s<i&&8==Qi[s]?1==n?1:8:256;for(let e=t;e<s;e++)Qi[e]=r;t=s-1}else 8==s&&1==n&&(Qi[t]=1);e=s,7&s&&(n=s)}}}(t,s,r,n,a),function(t,e,i,n,s){let r=1==s?2:1;for(let o=0,a=0,l=0;o<=n.length;o++){let h=o?n[o-1].to:e,c=o<n.length?n[o].from:i;for(let e,i,n,o=h;o<c;o++)if(i=vi[e=t.charCodeAt(o)])if(i<0){for(let t=a-3;t>=0;t-=3)if(bi[t+1]==-i){let e=bi[t+2],i=2&e?s:4&e?1&e?r:s:0;i&&(Qi[o]=Qi[bi[t]]=i),a=t;break}}else{if(189==bi.length)break;bi[a++]=o,bi[a++]=e,bi[a++]=l}else if(2==(n=Qi[o])||1==n){let t=n==s;l=t?0:1;for(let e=a-3;e>=0;e-=3){let i=bi[e+2];if(2&i)break;if(t)bi[e+2]|=2;else{if(4&i)break;bi[e+2]|=4}}}}}(t,s,r,n,a),function(t,e,i,n){for(let s=0,r=n;s<=i.length;s++){let o=s?i[s-1].to:t,a=s<i.length?i[s].from:e;for(let l=o;l<a;){let o=Qi[l];if(256==o){let o=l+1;for(;;)if(o==a){if(s==i.length)break;o=i[s++].to,a=s<i.length?i[s].from:e}else{if(256!=Qi[o])break;o++}let h=1==r,c=h==(1==(o<e?Qi[o]:n))?h?1:2:n;for(let e=o,n=s,r=n?i[n-1].to:t;e>l;)e==r&&(e=i[--n].from,r=n?i[n-1].to:t),Qi[--e]=c;l=o}else r=o,l++}}}(s,r,n,a),$i(t,s,r,e,i,n,o)}function Zi(t,e,i){if(!t)return[new xi(0,0,e==Oi?1:0)];if(e==pi&&!i.length&&!Si.test(t))return Ci(t.length);if(i.length)for(;t.length>Qi.length;)Qi[Qi.length]=256;let n=[],s=e==pi?0:1;return Pi(t,s,s,i,0,t.length,n),n}function Ci(t){return[new xi(0,t,0)]}let Ti="";function Ai(t,e,i,n,s){var r;let o=n.head-t.from,a=xi.find(e,o,null!==(r=n.bidiLevel)&&void 0!==r?r:-1,n.assoc),l=e[a],h=l.side(s,i);if(o==h){let t=a+=s?1:-1;if(t<0||t>=e.length)return null;l=e[a=t],o=l.side(!s,i),h=l.side(s,i)}let c=O(t.text,o,l.forward(s,i));(c<l.from||c>l.to)&&(c=h),Ti=t.text.slice(Math.min(o,c),Math.max(o,c));let f=a==(s?e.length-1:0)?null:e[a+(s?1:-1)];return f&&c==h&&f.level+(s?0:1)<l.level?Y.cursor(f.side(!s,i)+t.from,f.forward(s,i)?1:-1,f.level):Y.cursor(c+t.from,l.forward(s,i)?-1:1,l.level)}function Ri(t,e,i){for(let n=e;n<i;n++){let e=yi(t.charCodeAt(n));if(1==e)return pi;if(2==e||4==e)return Oi}return pi}const Xi=j.define(),Yi=j.define(),Wi=j.define(),Mi=j.define(),ji=j.define(),Di=j.define(),Ei=j.define(),qi=j.define({combine:t=>t.some((t=>t))}),_i=j.define({combine:t=>t.some((t=>t))});class Vi{constructor(t,e="nearest",i="nearest",n=5,s=5,r=!1){this.range=t,this.y=e,this.x=i,this.yMargin=n,this.xMargin=s,this.isSnapshot=r}map(t){return t.empty?this:new Vi(this.range.map(t),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}clip(t){return this.range.to<=t.doc.length?this:new Vi(Y.cursor(t.doc.length),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}}const Ii=dt.define({map:(t,e)=>t.map(e)});function zi(t,e,i){let n=t.facet(Mi);n.length?n[0](e):window.onerror?window.onerror(String(e),i,void 0,void 0,e):i?console.error(i+":",e):console.error(e)}const Bi=j.define({combine:t=>!t.length||t[0]});let Gi=0;const Li=j.define();class Ni{constructor(t,e,i,n,s){this.id=t,this.create=e,this.domEventHandlers=i,this.domEventObservers=n,this.extension=s(this)}static define(t,e){const{eventHandlers:i,eventObservers:n,provide:s,decorations:r}=e||{};return new Ni(Gi++,t,i,n,(t=>{let e=[Li.of(t)];return r&&e.push(Ji.of((e=>{let i=e.plugin(t);return i?r(i):si.none}))),s&&e.push(s(t)),e}))}static fromClass(t,e){return Ni.define((e=>new t(e)),e)}}class Ui{constructor(t){this.spec=t,this.mustUpdate=null,this.value=null}update(t){if(this.value){if(this.mustUpdate){let t=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(t)}catch(e){if(zi(t.state,e,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch(t){}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.create(t)}catch(e){zi(t.state,e,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(t){var e;if(null===(e=this.value)||void 0===e?void 0:e.destroy)try{this.value.destroy()}catch(e){zi(t.state,e,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}}const Hi=j.define(),Fi=j.define(),Ji=j.define(),Ki=j.define(),tn=j.define(),en=j.define();function nn(t,e){let i=t.state.facet(en);if(!i.length)return i;let n=i.map((e=>e instanceof Function?e(t):e)),s=[];return At.spans(n,e.from,e.to,{point(){},span(t,i,n,r){let o=t-e.from,a=i-e.from,l=s;for(let t=n.length-1;t>=0;t--,r--){let i,s=n[t].spec.bidiIsolate;if(null==s&&(s=Ri(e.text,o,a)),r>0&&l.length&&(i=l[l.length-1]).to==o&&i.direction==s)i.to=a,l=i.inner;else{let t={from:o,to:a,direction:s,inner:[]};l.push(t),l=t.inner}}}}),s}const sn=j.define();function rn(t){let e=0,i=0,n=0,s=0;for(let r of t.state.facet(sn)){let o=r(t);o&&(null!=o.left&&(e=Math.max(e,o.left)),null!=o.right&&(i=Math.max(i,o.right)),null!=o.top&&(n=Math.max(n,o.top)),null!=o.bottom&&(s=Math.max(s,o.bottom)))}return{left:e,right:i,top:n,bottom:s}}const on=j.define();class an{constructor(t,e,i,n){this.fromA=t,this.toA=e,this.fromB=i,this.toB=n}join(t){return new an(Math.min(this.fromA,t.fromA),Math.max(this.toA,t.toA),Math.min(this.fromB,t.fromB),Math.max(this.toB,t.toB))}addToSet(t){let e=t.length,i=this;for(;e>0;e--){let n=t[e-1];if(!(n.fromA>i.toA)){if(n.toA<i.fromA)break;i=i.join(n),t.splice(e-1,1)}}return t.splice(e,0,i),t}static extendWithRanges(t,e){if(0==e.length)return t;let i=[];for(let n=0,s=0,r=0,o=0;;n++){let a=n==t.length?null:t[n],l=r-o,h=a?a.fromB:1e9;for(;s<e.length&&e[s]<h;){let t=e[s],n=e[s+1],r=Math.max(o,t),a=Math.min(h,n);if(r<=a&&new an(r+l,a+l,r,a).addToSet(i),n>h)break;s+=2}if(!a)return i;new an(a.fromA,a.toA,a.fromB,a.toB).addToSet(i),r=a.toA,o=a.toB}}}class ln{constructor(t,e,i){this.view=t,this.state=e,this.transactions=i,this.flags=0,this.startState=t.state,this.changes=$.empty(this.startState.doc.length);for(let t of i)this.changes=this.changes.compose(t.changes);let n=[];this.changes.iterChangedRanges(((t,e,i,s)=>n.push(new an(t,e,i,s)))),this.changedRanges=n}static create(t,e,i){return new ln(t,e,i)}get viewportChanged(){return(4&this.flags)>0}get heightChanged(){return(2&this.flags)>0}get geometryChanged(){return this.docChanged||(10&this.flags)>0}get focusChanged(){return(1&this.flags)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some((t=>t.selection))}get empty(){return 0==this.flags&&0==this.transactions.length}}class hn extends Qe{get length(){return this.view.state.doc.length}constructor(t){super(),this.view=t,this.decorations=[],this.dynamicDecorationMap=[],this.domChanged=null,this.hasComposition=null,this.markedForComposition=new Set,this.minWidth=0,this.minWidthFrom=0,this.minWidthTo=0,this.impreciseAnchor=null,this.impreciseHead=null,this.forceSelection=!1,this.lastUpdate=Date.now(),this.setDOM(t.contentDOM),this.children=[new ti],this.children[0].setParent(this),this.updateDeco(),this.updateInner([new an(0,0,0,t.state.doc.length)],0,null)}update(t){var e;let i=t.changedRanges;this.minWidth>0&&i.length&&(i.every((({fromA:t,toA:e})=>e<this.minWidthFrom||t>this.minWidthTo))?(this.minWidthFrom=t.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=t.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0);let n=-1;this.view.inputState.composing>=0&&((null===(e=this.domChanged)||void 0===e?void 0:e.newSel)?n=this.domChanged.newSel.head:function(t,e){let i=!1;e&&t.iterChangedRanges(((t,n)=>{t<e.to&&n>e.from&&(i=!0)}));return i}(t.changes,this.hasComposition)||t.selectionSet||(n=t.state.selection.main.head));let s=n>-1?function(t,e,i){let n=fn(t,i);if(!n)return null;let{node:s,from:r,to:o}=n,a=s.nodeValue;if(/[\n\r]/.test(a))return null;if(t.state.doc.sliceString(n.from,n.to)!=a)return null;let l=e.invertedDesc,h=new an(l.mapPos(r),l.mapPos(o),r,o),c=[];for(let e=s.parentNode;;e=e.parentNode){let i=Qe.get(e);if(i instanceof Ie)c.push({node:e,deco:i.mark});else{if(i instanceof ti||"DIV"==e.nodeName&&e.parentNode==t.contentDOM)return{range:h,text:s,marks:c,line:e};if(e==t.contentDOM)return null;c.push({node:e,deco:new ri({inclusive:!0,attributes:Ke(e),tagName:e.tagName.toLowerCase()})})}}}(this.view,t.changes,n):null;if(this.domChanged=null,this.hasComposition){this.markedForComposition.clear();let{from:e,to:n}=this.hasComposition;i=new an(e,n,t.changes.mapPos(e,-1),t.changes.mapPos(n,1)).addToSet(i.slice())}this.hasComposition=s?{from:s.range.fromB,to:s.range.toB}:null,(_e.ie||_e.chrome)&&!s&&t&&t.state.doc.lines!=t.startState.doc.lines&&(this.forceSelection=!0);let r=function(t,e,i){let n=new dn;return At.compare(t,e,i,n),n.changes}(this.decorations,this.updateDeco(),t.changes);return i=an.extendWithRanges(i,r),!!(7&this.flags||0!=i.length)&&(this.updateInner(i,t.startState.doc.length,s),t.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(t,e,i){this.view.viewState.mustMeasureContent=!0,this.updateChildren(t,e,i);let{observer:n}=this.view;n.ignore((()=>{this.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let t=_e.chrome||_e.ios?{node:n.selectionRange.focusNode,written:!1}:void 0;this.sync(this.view,t),this.flags&=-8,t&&(t.written||n.selectionRange.focusNode!=t.node)&&(this.forceSelection=!0),this.dom.style.height=""})),this.markedForComposition.forEach((t=>t.flags&=-9));let s=[];if(this.view.viewport.from||this.view.viewport.to<this.view.state.doc.length)for(let t of this.children)t instanceof ei&&t.widget instanceof cn&&s.push(t.dom);n.updateGaps(s)}updateChildren(t,e,i){let n=i?i.range.addToSet(t.slice()):t,s=this.childCursor(e);for(let t=n.length-1;;t--){let e=t>=0?n[t]:null;if(!e)break;let r,o,a,l,{fromA:h,toA:c,fromB:f,toB:u}=e;if(i&&i.range.fromB<u&&i.range.toB>f){let t=ci.build(this.view.state.doc,f,i.range.fromB,this.decorations,this.dynamicDecorationMap),e=ci.build(this.view.state.doc,i.range.toB,u,this.decorations,this.dynamicDecorationMap);o=t.breakAtStart,a=t.openStart,l=e.openEnd;let n=this.compositionView(i);e.breakAtStart?n.breakAfter=1:e.content.length&&n.merge(n.length,n.length,e.content[0],!1,e.openStart,0)&&(n.breakAfter=e.content[0].breakAfter,e.content.shift()),t.content.length&&n.merge(0,0,t.content[t.content.length-1],!0,0,t.openEnd)&&t.content.pop(),r=t.content.concat(n).concat(e.content)}else({content:r,breakAtStart:o,openStart:a,openEnd:l}=ci.build(this.view.state.doc,f,u,this.decorations,this.dynamicDecorationMap));let{i:d,off:p}=s.findPos(c,1),{i:O,off:g}=s.findPos(h,-1);Ze(this,O,g,d,p,r,o,a,l)}i&&this.fixCompositionDOM(i)}compositionView(t){let e=new Ve(t.text.nodeValue);e.flags|=8;for(let{deco:i}of t.marks)e=new Ie(i,[e],e.length);let i=new ti;return i.append(e,0),i}fixCompositionDOM(t){let e=(t,e)=>{e.flags|=8|(e.children.some((t=>7&t.flags))?1:0),this.markedForComposition.add(e);let i=Qe.get(t);i&&i!=e&&(i.dom=null),e.setDOM(t)},i=this.childPos(t.range.fromB,1),n=this.children[i.i];e(t.line,n);for(let s=t.marks.length-1;s>=-1;s--)i=n.childPos(i.off,1),n=n.children[i.i],e(s>=0?t.marks[s].node:t.text,n)}updateSelection(t=!1,e=!1){!t&&this.view.observer.selectionRange.focusNode||this.view.observer.readSelectionRange();let i=this.view.root.activeElement,n=i==this.dom,s=!n&&oe(this.dom,this.view.observer.selectionRange)&&!(i&&this.dom.contains(i));if(!(n||e||s))return;let r=this.forceSelection;this.forceSelection=!1;let o=this.view.state.selection.main,a=this.moveToLine(this.domAtPos(o.anchor)),l=o.empty?a:this.moveToLine(this.domAtPos(o.head));if(_e.gecko&&o.empty&&!this.hasComposition&&(1==(h=a).node.nodeType&&h.node.firstChild&&(0==h.offset||"false"==h.node.childNodes[h.offset-1].contentEditable)&&(h.offset==h.node.childNodes.length||"false"==h.node.childNodes[h.offset].contentEditable))){let t=document.createTextNode("");this.view.observer.ignore((()=>a.node.insertBefore(t,a.node.childNodes[a.offset]||null))),a=l=new xe(t,0),r=!0}var h;let c=this.view.observer.selectionRange;!r&&c.focusNode&&(le(a.node,a.offset,c.anchorNode,c.anchorOffset)&&le(l.node,l.offset,c.focusNode,c.focusOffset)||this.suppressWidgetCursorChange(c,o))||(this.view.observer.ignore((()=>{_e.android&&_e.chrome&&this.dom.contains(c.focusNode)&&function(t,e){for(let i=t;i&&i!=e;i=i.assignedSlot||i.parentNode)if(1==i.nodeType&&"false"==i.contentEditable)return!0;return!1}(c.focusNode,this.dom)&&(this.dom.blur(),this.dom.focus({preventScroll:!0}));let t=se(this.view.root);if(t)if(o.empty){if(_e.gecko){let t=(e=a.node,n=a.offset,1!=e.nodeType?0:(n&&"false"==e.childNodes[n-1].contentEditable?1:0)|(n<e.childNodes.length&&"false"==e.childNodes[n].contentEditable?2:0));if(t&&3!=t){let e=un(a.node,a.offset,1==t?1:-1);e&&(a=new xe(e.node,e.offset))}}t.collapse(a.node,a.offset),null!=o.bidiLevel&&void 0!==t.caretBidiLevel&&(t.caretBidiLevel=o.bidiLevel)}else if(t.extend){t.collapse(a.node,a.offset);try{t.extend(l.node,l.offset)}catch(t){}}else{let e=document.createRange();o.anchor>o.head&&([a,l]=[l,a]),e.setEnd(l.node,l.offset),e.setStart(a.node,a.offset),t.removeAllRanges(),t.addRange(e)}else;var e,n;s&&this.view.root.activeElement==this.dom&&(this.dom.blur(),i&&i.focus())})),this.view.observer.setSelectionRange(a,l)),this.impreciseAnchor=a.precise?null:new xe(c.anchorNode,c.anchorOffset),this.impreciseHead=l.precise?null:new xe(c.focusNode,c.focusOffset)}suppressWidgetCursorChange(t,e){return this.hasComposition&&e.empty&&le(t.focusNode,t.focusOffset,t.anchorNode,t.anchorOffset)&&this.posFromDOM(t.focusNode,t.focusOffset)==e.head}enforceCursorAssoc(){if(this.hasComposition)return;let{view:t}=this,e=t.state.selection.main,i=se(t.root),{anchorNode:n,anchorOffset:s}=t.observer.selectionRange;if(!(i&&e.empty&&e.assoc&&i.modify))return;let r=ti.find(this,e.head);if(!r)return;let o=r.posAtStart;if(e.head==o||e.head==o+r.length)return;let a=this.coordsAt(e.head,-1),l=this.coordsAt(e.head,1);if(!a||!l||a.bottom>l.top)return;let h=this.domAtPos(e.head+e.assoc);i.collapse(h.node,h.offset),i.modify("move",e.assoc<0?"forward":"backward","lineboundary"),t.observer.readSelectionRange();let c=t.observer.selectionRange;t.docView.posFromDOM(c.anchorNode,c.anchorOffset)!=e.from&&i.collapse(n,s)}moveToLine(t){let e,i=this.dom;if(t.node!=i)return t;for(let n=t.offset;!e&&n<i.childNodes.length;n++){let t=Qe.get(i.childNodes[n]);t instanceof ti&&(e=t.domAtPos(0))}for(let n=t.offset-1;!e&&n>=0;n--){let t=Qe.get(i.childNodes[n]);t instanceof ti&&(e=t.domAtPos(t.length))}return e?new xe(e.node,e.offset,!0):t}nearest(t){for(let e=t;e;){let t=Qe.get(e);if(t&&t.rootView==this)return t;e=e.parentNode}return null}posFromDOM(t,e){let i=this.nearest(t);if(!i)throw new RangeError("Trying to find position for a DOM position outside of the document");return i.localPosFromDOM(t,e)+i.posAtStart}domAtPos(t){let{i:e,off:i}=this.childCursor().findPos(t,-1);for(;e<this.children.length-1;){let t=this.children[e];if(i<t.length||t instanceof ti)break;e++,i=0}return this.children[e].domAtPos(i)}coordsAt(t,e){let i=null,n=0;for(let s=this.length,r=this.children.length-1;r>=0;r--){let o=this.children[r],a=s-o.breakAfter,l=a-o.length;if(a<t)break;l<=t&&(l<t||o.covers(-1))&&(a>t||o.covers(1))&&(!i||o instanceof ti&&!(i instanceof ti&&e>=0))&&(i=o,n=l),s=l}return i?i.coordsAt(t-n,e):null}coordsForChar(t){let{i:e,off:i}=this.childPos(t,1),n=this.children[e];if(!(n instanceof ti))return null;for(;n.children.length;){let{i:t,off:e}=n.childPos(i,1);for(;;t++){if(t==n.children.length)return null;if((n=n.children[t]).length)break}i=e}if(!(n instanceof Ve))return null;let s=O(n.text,i);if(s==i)return null;let r=ve(n.dom,i,s).getClientRects();for(let t=0;t<r.length;t++){let e=r[t];if(t==r.length-1||e.top<e.bottom&&e.left<e.right)return e}return null}measureVisibleLineHeights(t){let e=[],{from:i,to:n}=t,s=this.view.contentDOM.clientWidth,r=s>Math.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,o=-1,a=this.view.textDirection==di.LTR;for(let t=0,l=0;l<this.children.length;l++){let h=this.children[l],c=t+h.length;if(c>n)break;if(t>=i){let i=h.dom.getBoundingClientRect();if(e.push(i.height),r){let e=h.dom.lastChild,n=e?ae(e):[];if(n.length){let e=n[n.length-1],r=a?e.right-i.left:i.right-e.left;r>o&&(o=r,this.minWidth=s,this.minWidthFrom=t,this.minWidthTo=c)}}}t=c+h.breakAfter}return e}textDirectionAt(t){let{i:e}=this.childPos(t,1);return"rtl"==getComputedStyle(this.children[e].dom).direction?di.RTL:di.LTR}measureTextSize(){for(let t of this.children)if(t instanceof ti){let e=t.measureTextSize();if(e)return e}let t,e,i,n=document.createElement("div");return n.className="cm-line",n.style.width="99999px",n.style.position="absolute",n.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore((()=>{this.dom.appendChild(n);let s=ae(n.firstChild)[0];t=n.getBoundingClientRect().height,e=s?s.width/27:7,i=s?s.height:t,n.remove()})),{lineHeight:t,charWidth:e,textHeight:i}}childCursor(t=this.length){let e=this.children.length;return e&&(t-=this.children[--e].length),new Pe(this.children,t,e)}computeBlockGapDeco(){let t=[],e=this.view.viewState;for(let i=0,n=0;;n++){let s=n==e.viewports.length?null:e.viewports[n],r=s?s.from-1:this.length;if(r>i){let n=(e.lineBlockAt(r).bottom-e.lineBlockAt(i).top)/this.view.scaleY;t.push(si.replace({widget:new cn(n),block:!0,inclusive:!0,isBlockGap:!0}).range(i,r))}if(!s)break;i=s.to+1}return si.set(t)}updateDeco(){let t=this.view.state.facet(Ji).map(((t,e)=>(this.dynamicDecorationMap[e]="function"==typeof t)?t(this.view):t)),e=!1,i=this.view.state.facet(Ki).map(((t,i)=>{let n="function"==typeof t;return n&&(e=!0),n?t(this.view):t}));i.length&&(this.dynamicDecorationMap[t.length]=e,t.push(At.join(i)));for(let e=t.length;e<t.length+3;e++)this.dynamicDecorationMap[e]=!1;return this.decorations=[...t,this.computeBlockGapDeco(),this.view.viewState.lineGapDeco]}scrollIntoView(t){if(t.isSnapshot){let e=this.view.viewState.lineBlockAt(t.range.head);return this.view.scrollDOM.scrollTop=e.top-t.yMargin,void(this.view.scrollDOM.scrollLeft=t.xMargin)}let e,{range:i}=t,n=this.coordsAt(i.head,i.empty?i.assoc:i.head>i.anchor?-1:1);if(!n)return;!i.empty&&(e=this.coordsAt(i.anchor,i.anchor>i.head?-1:1))&&(n={left:Math.min(n.left,e.left),top:Math.min(n.top,e.top),right:Math.max(n.right,e.right),bottom:Math.max(n.bottom,e.bottom)});let s=rn(this.view),r={left:n.left-s.left,top:n.top-s.top,right:n.right+s.right,bottom:n.bottom+s.bottom},{offsetWidth:o,offsetHeight:a}=this.view.scrollDOM;!function(t,e,i,n,s,r,o,a){let l=t.ownerDocument,h=l.defaultView||window;for(let c=t,f=!1;c&&!f;)if(1==c.nodeType){let t,u=c==l.body,d=1,p=1;if(u)t=de(h);else{if(/^(fixed|sticky)$/.test(getComputedStyle(c).position)&&(f=!0),c.scrollHeight<=c.clientHeight&&c.scrollWidth<=c.clientWidth){c=c.assignedSlot||c.parentNode;continue}let e=c.getBoundingClientRect();({scaleX:d,scaleY:p}=pe(c,e)),t={left:e.left,right:e.left+c.clientWidth*d,top:e.top,bottom:e.top+c.clientHeight*p}}let O=0,g=0;if("nearest"==s)e.top<t.top?(g=-(t.top-e.top+o),i>0&&e.bottom>t.bottom+g&&(g=e.bottom-t.bottom+g+o)):e.bottom>t.bottom&&(g=e.bottom-t.bottom+o,i<0&&e.top-g<t.top&&(g=-(t.top+g-e.top+o)));else{let n=e.bottom-e.top,r=t.bottom-t.top;g=("center"==s&&n<=r?e.top+n/2-r/2:"start"==s||"center"==s&&i<0?e.top-o:e.bottom-r+o)-t.top}if("nearest"==n?e.left<t.left?(O=-(t.left-e.left+r),i>0&&e.right>t.right+O&&(O=e.right-t.right+O+r)):e.right>t.right&&(O=e.right-t.right+r,i<0&&e.left<t.left+O&&(O=-(t.left+O-e.left+r))):O=("center"==n?e.left+(e.right-e.left)/2-(t.right-t.left)/2:"start"==n==a?e.left-r:e.right-(t.right-t.left)+r)-t.left,O||g)if(u)h.scrollBy(O,g);else{let t=0,i=0;if(g){let t=c.scrollTop;c.scrollTop+=g/p,i=(c.scrollTop-t)*p}if(O){let e=c.scrollLeft;c.scrollLeft+=O/d,t=(c.scrollLeft-e)*d}e={left:e.left-t,top:e.top-i,right:e.right-t,bottom:e.bottom-i},t&&Math.abs(t-O)<1&&(n="nearest"),i&&Math.abs(i-g)<1&&(s="nearest")}if(u)break;c=c.assignedSlot||c.parentNode}else{if(11!=c.nodeType)break;c=c.host}}(this.view.scrollDOM,r,i.head<i.anchor?-1:1,t.x,t.y,Math.max(Math.min(t.xMargin,o),-o),Math.max(Math.min(t.yMargin,a),-a),this.view.textDirection==di.LTR)}}class cn extends ii{constructor(t){super(),this.height=t}toDOM(){let t=document.createElement("div");return t.className="cm-gap",this.updateDOM(t),t}eq(t){return t.height==this.height}updateDOM(t){return t.style.height=this.height+"px",!0}get editable(){return!0}get estimatedHeight(){return this.height}}function fn(t,e){let i=t.observer.selectionRange,n=i.focusNode&&un(i.focusNode,i.focusOffset,0);if(!n)return null;let s=e-n.offset;return{from:s,to:s+n.node.nodeValue.length,node:n.node}}function un(t,e,i){if(i<=0)for(let i=t,n=e;;){if(3==i.nodeType)return{node:i,offset:n};if(!(1==i.nodeType&&n>0))break;i=i.childNodes[n-1],n=fe(i)}if(i>=0)for(let n=t,s=e;;){if(3==n.nodeType)return{node:n,offset:s};if(!(1==n.nodeType&&s<n.childNodes.length&&i>=0))break;n=n.childNodes[s],s=0}return null}let dn=class{constructor(){this.changes=[]}compareRange(t,e){hi(t,e,this.changes)}comparePoint(t,e){hi(t,e,this.changes)}};function pn(t,e){return e.left>t?e.left-t:Math.max(0,t-e.right)}function On(t,e){return e.top>t?e.top-t:Math.max(0,t-e.bottom)}function gn(t,e){return t.top<e.bottom-1&&t.bottom>e.top+1}function mn(t,e){return e<t.top?{top:e,left:t.left,right:t.right,bottom:t.bottom}:t}function wn(t,e){return e>t.bottom?{top:t.top,left:t.left,right:t.right,bottom:e}:t}function vn(t,e,i){let n,s,r,o,a,l,h,c,f=!1;for(let u=t.firstChild;u;u=u.nextSibling){let t=ae(u);for(let d=0;d<t.length;d++){let p=t[d];s&&gn(s,p)&&(p=mn(wn(p,s.bottom),s.top));let O=pn(e,p),g=On(i,p);if(0==O&&0==g)return 3==u.nodeType?bn(u,e,i):vn(u,e,i);if(!n||o>g||o==g&&r>O){n=u,s=p,r=O,o=g;let a=g?i<p.top?-1:1:O?e<p.left?-1:1:0;f=!a||(a>0?d<t.length-1:d>0)}0==O?i>p.bottom&&(!h||h.bottom<p.bottom)?(a=u,h=p):i<p.top&&(!c||c.top>p.top)&&(l=u,c=p):h&&gn(h,p)?h=wn(h,p.bottom):c&&gn(c,p)&&(c=mn(c,p.top))}}if(h&&h.bottom>=i?(n=a,s=h):c&&c.top<=i&&(n=l,s=c),!n)return{node:t,offset:0};let u=Math.max(s.left,Math.min(s.right,e));return 3==n.nodeType?bn(n,u,i):f&&"false"!=n.contentEditable?vn(n,u,i):{node:t,offset:Array.prototype.indexOf.call(t.childNodes,n)+(e>=(s.left+s.right)/2?1:0)}}function bn(t,e,i){let n=t.nodeValue.length,s=-1,r=1e9,o=0;for(let a=0;a<n;a++){let n=ve(t,a,a+1).getClientRects();for(let l=0;l<n.length;l++){let h=n[l];if(h.top==h.bottom)continue;o||(o=e-h.left);let c=(h.top>i?h.top-i:i-h.bottom)-1;if(h.left-1<=e&&h.right+1>=e&&c<r){let i=e>=(h.left+h.right)/2,n=i;if(_e.chrome||_e.gecko){ve(t,a).getBoundingClientRect().left==h.right&&(n=!i)}if(c<=0)return{node:t,offset:a+(n?1:0)};s=a+(n?1:0),r=c}}}return{node:t,offset:s>-1?s:o>0?t.nodeValue.length:0}}function yn(t,e,i,n=-1){var s,r;let o,a=t.contentDOM.getBoundingClientRect(),l=a.top+t.viewState.paddingTop,{docHeight:h}=t.viewState,{x:c,y:f}=e,u=f-l;if(u<0)return 0;if(u>h)return t.state.doc.length;for(let e=t.viewState.heightOracle.textHeight/2,s=!1;o=t.elementAtHeight(u),o.type!=ni.Text;)for(;u=n>0?o.bottom+e:o.top-e,!(u>=0&&u<=h);){if(s)return i?null:0;s=!0,n=-n}f=l+u;let d=o.from;if(d<t.viewport.from)return 0==t.viewport.from?0:i?null:Sn(t,a,o,c,f);if(d>t.viewport.to)return t.viewport.to==t.state.doc.length?t.state.doc.length:i?null:Sn(t,a,o,c,f);let p=t.dom.ownerDocument,O=t.root.elementFromPoint?t.root:p,g=O.elementFromPoint(c,f);g&&!t.contentDOM.contains(g)&&(g=null),g||(c=Math.max(a.left+1,Math.min(a.right-1,c)),g=O.elementFromPoint(c,f),g&&!t.contentDOM.contains(g)&&(g=null));let m,w=-1;if(g&&0!=(null===(s=t.docView.nearest(g))||void 0===s?void 0:s.isEditable))if(p.caretPositionFromPoint){let t=p.caretPositionFromPoint(c,f);t&&({offsetNode:m,offset:w}=t)}else if(p.caretRangeFromPoint){let e=p.caretRangeFromPoint(c,f);e&&(({startContainer:m,startOffset:w}=e),(!t.contentDOM.contains(m)||_e.safari&&function(t,e,i){let n;if(3!=t.nodeType||e!=(n=t.nodeValue.length))return!1;for(let e=t.nextSibling;e;e=e.nextSibling)if(1!=e.nodeType||"BR"!=e.nodeName)return!1;return ve(t,n-1,n).getBoundingClientRect().left>i}(m,w,c)||_e.chrome&&function(t,e,i){if(0!=e)return!1;for(let e=t;;){let t=e.parentNode;if(!t||1!=t.nodeType||t.firstChild!=e)return!1;if(t.classList.contains("cm-line"))break;e=t}let n=1==t.nodeType?t.getBoundingClientRect():ve(t,0,Math.max(t.nodeValue.length,1)).getBoundingClientRect();return i-n.left>5}(m,w,c))&&(m=void 0))}if(!m||!t.docView.dom.contains(m)){let e=ti.find(t.docView,d);if(!e)return u>o.top+o.height/2?o.to:o.from;({node:m,offset:w}=vn(e.dom,c,f))}let v=t.docView.nearest(m);if(!v)return null;if(v.isWidget&&1==(null===(r=v.dom)||void 0===r?void 0:r.nodeType)){let t=v.dom.getBoundingClientRect();return e.y<t.top||e.y<=t.bottom&&e.x<=(t.left+t.right)/2?v.posAtStart:v.posAtEnd}return v.localPosFromDOM(m,w)+v.posAtStart}function Sn(t,e,i,n,s){let r=Math.round((n-e.left)*t.defaultCharacterWidth);if(t.lineWrapping&&i.height>1.5*t.defaultLineHeight){let e=t.viewState.heightOracle.textHeight;r+=Math.floor((s-i.top-.5*(t.defaultLineHeight-e))/e)*t.viewState.heightOracle.lineLength}let o=t.state.sliceDoc(i.from,i.to);return i.from+zt(o,r,t.state.tabSize)}function xn(t,e){let i=t.lineBlockAt(e);if(Array.isArray(i.type))for(let t of i.type)if(t.to>e||t.to==e&&(t.to==i.to||t.type==ni.Text))return t;return i}function kn(t,e,i,n){let s=t.state.doc.lineAt(e.head),r=t.bidiSpans(s),o=t.textDirectionAt(s.from);for(let a=e,l=null;;){let e=Ai(s,r,o,a,i),h=Ti;if(!e){if(s.number==(i?t.state.doc.lines:1))return a;h="\n",s=t.state.doc.line(s.number+(i?1:-1)),r=t.bidiSpans(s),e=t.visualLineSide(s,!i)}if(l){if(!l(h))return a}else{if(!n)return e;l=n(h)}a=e}}function Qn(t,e,i){for(;;){let n=0;for(let s of t)s.between(e-1,e+1,((t,s,r)=>{if(e>t&&e<s){let r=n||i||(e-t<s-e?-1:1);e=r<0?t:s,n=r}}));if(!n)return e}}function $n(t,e,i){let n=Qn(t.state.facet(tn).map((e=>e(t))),i.from,e.head>i.from?-1:1);return n==i.from?i:Y.cursor(n,n<i.from?1:-1)}class Pn{setSelectionOrigin(t){this.lastSelectionOrigin=t,this.lastSelectionTime=Date.now()}constructor(t){this.view=t,this.lastKeyCode=0,this.lastKeyTime=0,this.lastTouchTime=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.pendingIOSKey=void 0,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastEscPress=0,this.lastContextMenu=0,this.scrollHandlers=[],this.handlers=Object.create(null),this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.compositionPendingKey=!1,this.compositionPendingChange=!1,this.mouseSelection=null,this.draggedContent=null,this.handleEvent=this.handleEvent.bind(this),this.notifiedFocused=t.hasFocus,_e.safari&&t.contentDOM.addEventListener("input",(()=>null)),_e.gecko&&function(t){ts.has(t)||(ts.add(t),t.addEventListener("copy",(()=>{})),t.addEventListener("cut",(()=>{})))}(t.contentDOM.ownerDocument)}handleEvent(t){(function(t,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let i,n=e.target;n!=t.contentDOM;n=n.parentNode)if(!n||11==n.nodeType||(i=Qe.get(n))&&i.ignoreEvent(e))return!1;return!0})(this.view,t)&&!this.ignoreDuringComposition(t)&&("keydown"==t.type&&this.keydown(t)||this.runHandlers(t.type,t))}runHandlers(t,e){let i=this.handlers[t];if(i){for(let t of i.observers)t(this.view,e);for(let t of i.handlers){if(e.defaultPrevented)break;if(t(this.view,e)){e.preventDefault();break}}}}ensureHandlers(t){let e=Cn(t),i=this.handlers,n=this.view.contentDOM;for(let t in e)if("scroll"!=t){let s=!e[t].handlers.length,r=i[t];r&&s!=!r.handlers.length&&(n.removeEventListener(t,this.handleEvent),r=null),r||n.addEventListener(t,this.handleEvent,{passive:s})}for(let t in i)"scroll"==t||e[t]||n.removeEventListener(t,this.handleEvent);this.handlers=e}keydown(t){if(this.lastKeyCode=t.keyCode,this.lastKeyTime=Date.now(),9==t.keyCode&&Date.now()<this.lastEscPress+2e3)return!0;if(27!=t.keyCode&&Rn.indexOf(t.keyCode)<0&&(this.view.inputState.lastEscPress=0),_e.android&&_e.chrome&&!t.synthetic&&(13==t.keyCode||8==t.keyCode))return this.view.observer.delayAndroidKey(t.key,t.keyCode),!0;let e;return!_e.ios||t.synthetic||t.altKey||t.metaKey||!((e=Tn.find((e=>e.keyCode==t.keyCode)))&&!t.ctrlKey||An.indexOf(t.key)>-1&&t.ctrlKey&&!t.shiftKey)?(229!=t.keyCode&&this.view.observer.forceFlush(),!1):(this.pendingIOSKey=e||t,setTimeout((()=>this.flushIOSKey()),250),!0)}flushIOSKey(){let t=this.pendingIOSKey;return!!t&&(this.pendingIOSKey=void 0,be(this.view.contentDOM,t.key,t.keyCode))}ignoreDuringComposition(t){return!!/^key/.test(t.type)&&(this.composing>0||!!(_e.safari&&!_e.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100)&&(this.compositionPendingKey=!1,!0))}startMouseSelection(t){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=t}update(t){this.mouseSelection&&this.mouseSelection.update(t),this.draggedContent&&t.docChanged&&(this.draggedContent=this.draggedContent.map(t.changes)),t.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}}function Zn(t,e){return(i,n)=>{try{return e.call(t,n,i)}catch(t){zi(i.state,t)}}}function Cn(t){let e=Object.create(null);function i(t){return e[t]||(e[t]={observers:[],handlers:[]})}for(let e of t){let t=e.spec;if(t&&t.domEventHandlers)for(let n in t.domEventHandlers){let s=t.domEventHandlers[n];s&&i(n).handlers.push(Zn(e.value,s))}if(t&&t.domEventObservers)for(let n in t.domEventObservers){let s=t.domEventObservers[n];s&&i(n).observers.push(Zn(e.value,s))}}for(let t in Wn)i(t).handlers.push(Wn[t]);for(let t in Mn)i(t).observers.push(Mn[t]);return e}const Tn=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],An="dthko",Rn=[16,17,18,20,91,92,224,225];function Xn(t){return.7*Math.max(0,t)+8}class Yn{constructor(t,e,i,n){this.view=t,this.startEvent=e,this.style=i,this.mustSelect=n,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=e,this.scrollParent=function(t){let e=t.ownerDocument;for(let i=t.parentNode;i&&i!=e.body;)if(1==i.nodeType){if(i.scrollHeight>i.clientHeight||i.scrollWidth>i.clientWidth)return i;i=i.assignedSlot||i.parentNode}else{if(11!=i.nodeType)break;i=i.host}return null}(t.contentDOM),this.atoms=t.state.facet(tn).map((e=>e(t)));let s=t.contentDOM.ownerDocument;s.addEventListener("mousemove",this.move=this.move.bind(this)),s.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=e.shiftKey,this.multiple=t.state.facet(Qt.allowMultipleSelections)&&function(t,e){let i=t.state.facet(Xi);return i.length?i[0](e):_e.mac?e.metaKey:e.ctrlKey}(t,e),this.dragging=!(!function(t,e){let{main:i}=t.state.selection;if(i.empty)return!1;let n=se(t.root);if(!n||0==n.rangeCount)return!0;let s=n.getRangeAt(0).getClientRects();for(let t=0;t<s.length;t++){let i=s[t];if(i.left<=e.clientX&&i.right>=e.clientX&&i.top<=e.clientY&&i.bottom>=e.clientY)return!0}return!1}(t,e)||1!=Nn(e))&&null}start(t){!1===this.dragging&&this.select(t)}move(t){var e,i,n;if(0==t.buttons)return this.destroy();if(this.dragging||null==this.dragging&&(i=this.startEvent,n=t,Math.max(Math.abs(i.clientX-n.clientX),Math.abs(i.clientY-n.clientY))<10))return;this.select(this.lastEvent=t);let s=0,r=0,o=(null===(e=this.scrollParent)||void 0===e?void 0:e.getBoundingClientRect())||{left:0,top:0,right:this.view.win.innerWidth,bottom:this.view.win.innerHeight},a=rn(this.view);t.clientX-a.left<=o.left+6?s=-Xn(o.left-t.clientX):t.clientX+a.right>=o.right-6&&(s=Xn(t.clientX-o.right)),t.clientY-a.top<=o.top+6?r=-Xn(o.top-t.clientY):t.clientY+a.bottom>=o.bottom-6&&(r=Xn(t.clientY-o.bottom)),this.setScrollSpeed(s,r)}up(t){null==this.dragging&&this.select(this.lastEvent),this.dragging||t.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let t=this.view.contentDOM.ownerDocument;t.removeEventListener("mousemove",this.move),t.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=this.view.inputState.draggedContent=null}setScrollSpeed(t,e){this.scrollSpeed={x:t,y:e},t||e?this.scrolling<0&&(this.scrolling=setInterval((()=>this.scroll()),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){this.scrollParent?(this.scrollParent.scrollLeft+=this.scrollSpeed.x,this.scrollParent.scrollTop+=this.scrollSpeed.y):this.view.win.scrollBy(this.scrollSpeed.x,this.scrollSpeed.y),!1===this.dragging&&this.select(this.lastEvent)}skipAtoms(t){let e=null;for(let i=0;i<t.ranges.length;i++){let n=t.ranges[i],s=null;if(n.empty){let t=Qn(this.atoms,n.from,0);t!=n.from&&(s=Y.cursor(t,-1))}else{let t=Qn(this.atoms,n.from,-1),e=Qn(this.atoms,n.to,1);t==n.from&&e==n.to||(s=Y.range(n.from==n.anchor?t:e,n.from==n.head?t:e))}s&&(e||(e=t.ranges.slice()),e[i]=s)}return e?Y.create(e,t.mainIndex):t}select(t){let{view:e}=this,i=this.skipAtoms(this.style.get(t,this.extend,this.multiple));!this.mustSelect&&i.eq(e.state.selection,!1===this.dragging)||this.view.dispatch({selection:i,userEvent:"select.pointer"}),this.mustSelect=!1}update(t){this.style.update(t)&&setTimeout((()=>this.select(this.lastEvent)),20)}}const Wn=Object.create(null),Mn=Object.create(null),jn=_e.ie&&_e.ie_version<15||_e.ios&&_e.webkit_version<604;function Dn(t,e){let i,{state:n}=t,s=1,r=n.toText(e),o=r.lines==n.selection.ranges.length;if(null!=Hn&&n.selection.ranges.every((t=>t.empty))&&Hn==r.toString()){let t=-1;i=n.changeByRange((i=>{let a=n.doc.lineAt(i.from);if(a.from==t)return{range:i};t=a.from;let l=n.toText((o?r.line(s++).text:e)+n.lineBreak);return{changes:{from:a.from,insert:l},range:Y.cursor(i.from+l.length)}}))}else i=o?n.changeByRange((t=>{let e=r.line(s++);return{changes:{from:t.from,to:t.to,insert:e.text},range:Y.cursor(t.from+e.length)}})):n.replaceSelection(r);t.dispatch(i,{userEvent:"input.paste",scrollIntoView:!0})}function En(t,e,i,n){if(1==n)return Y.cursor(e,i);if(2==n)return function(t,e,i=1){let n=t.charCategorizer(e),s=t.doc.lineAt(e),r=e-s.from;if(0==s.length)return Y.cursor(e);0==r?i=1:r==s.length&&(i=-1);let o=r,a=r;i<0?o=O(s.text,r,!1):a=O(s.text,r);let l=n(s.text.slice(o,a));for(;o>0;){let t=O(s.text,o,!1);if(n(s.text.slice(t,o))!=l)break;o=t}for(;a<s.length;){let t=O(s.text,a);if(n(s.text.slice(a,t))!=l)break;a=t}return Y.range(o+s.from,a+s.from)}(t.state,e,i);{let i=ti.find(t.docView,e),n=t.state.doc.lineAt(i?i.posAtEnd:e),s=i?i.posAtStart:n.from,r=i?i.posAtEnd:n.to;return r<t.state.doc.length&&r==n.to&&r++,Y.range(s,r)}}Mn.scroll=t=>{t.inputState.lastScrollTop=t.scrollDOM.scrollTop,t.inputState.lastScrollLeft=t.scrollDOM.scrollLeft},Wn.keydown=(t,e)=>(t.inputState.setSelectionOrigin("select"),27==e.keyCode&&(t.inputState.lastEscPress=Date.now()),!1),Mn.touchstart=(t,e)=>{t.inputState.lastTouchTime=Date.now(),t.inputState.setSelectionOrigin("select.pointer")},Mn.touchmove=t=>{t.inputState.setSelectionOrigin("select.pointer")},Wn.mousedown=(t,e)=>{if(t.observer.flush(),t.inputState.lastTouchTime>Date.now()-2e3)return!1;let i=null;for(let n of t.state.facet(Wi))if(i=n(t,e),i)break;if(i||0!=e.button||(i=function(t,e){let i=In(t,e),n=Nn(e),s=t.state.selection;return{update(t){t.docChanged&&(i.pos=t.changes.mapPos(i.pos),s=s.map(t.changes))},get(e,r,o){let a,l=In(t,e),h=En(t,l.pos,l.bias,n);if(i.pos!=l.pos&&!r){let e=En(t,i.pos,i.bias,n),s=Math.min(e.from,h.from),r=Math.max(e.to,h.to);h=s<h.from?Y.range(s,r):Y.range(r,s)}return r?s.replaceRange(s.main.extend(h.from,h.to)):o&&1==n&&s.ranges.length>1&&(a=function(t,e){for(let i=0;i<t.ranges.length;i++){let{from:n,to:s}=t.ranges[i];if(n<=e&&s>=e)return Y.create(t.ranges.slice(0,i).concat(t.ranges.slice(i+1)),t.mainIndex==i?0:t.mainIndex-(t.mainIndex>i?1:0))}return null}(s,l.pos))?a:o?s.addRange(h):Y.create([h])}}}(t,e)),i){let n=!t.hasFocus;t.inputState.startMouseSelection(new Yn(t,e,i,n)),n&&t.observer.ignore((()=>we(t.contentDOM)));let s=t.inputState.mouseSelection;if(s)return s.start(e),!1===s.dragging}return!1};let qn=(t,e)=>t>=e.top&&t<=e.bottom,_n=(t,e,i)=>qn(e,i)&&t>=i.left&&t<=i.right;function Vn(t,e,i,n){let s=ti.find(t.docView,e);if(!s)return 1;let r=e-s.posAtStart;if(0==r)return 1;if(r==s.length)return-1;let o=s.coordsAt(r,-1);if(o&&_n(i,n,o))return-1;let a=s.coordsAt(r,1);return a&&_n(i,n,a)?1:o&&qn(n,o)?-1:1}function In(t,e){let i=t.posAtCoords({x:e.clientX,y:e.clientY},!1);return{pos:i,bias:Vn(t,i,e.clientX,e.clientY)}}const zn=_e.ie&&_e.ie_version<=11;let Bn=null,Gn=0,Ln=0;function Nn(t){if(!zn)return t.detail;let e=Bn,i=Ln;return Bn=t,Ln=Date.now(),Gn=!e||i>Date.now()-400&&Math.abs(e.clientX-t.clientX)<2&&Math.abs(e.clientY-t.clientY)<2?(Gn+1)%3:1}function Un(t,e,i,n){if(!i)return;let s=t.posAtCoords({x:e.clientX,y:e.clientY},!1),{draggedContent:r}=t.inputState,o=n&&r&&function(t,e){let i=t.state.facet(Yi);return i.length?i[0](e):_e.mac?!e.altKey:!e.ctrlKey}(t,e)?{from:r.from,to:r.to}:null,a={from:s,insert:i},l=t.state.changes(o?[o,a]:a);t.focus(),t.dispatch({changes:l,selection:{anchor:l.mapPos(s,-1),head:l.mapPos(s,1)},userEvent:o?"move.drop":"input.drop"}),t.inputState.draggedContent=null}Wn.dragstart=(t,e)=>{let{selection:{main:i}}=t.state;if(e.target.draggable){let n=t.docView.nearest(e.target);if(n&&n.isWidget){let t=n.posAtStart,e=t+n.length;(t>=i.to||e<=i.from)&&(i=Y.range(t,e))}}let{inputState:n}=t;return n.mouseSelection&&(n.mouseSelection.dragging=!0),n.draggedContent=i,e.dataTransfer&&(e.dataTransfer.setData("Text",t.state.sliceDoc(i.from,i.to)),e.dataTransfer.effectAllowed="copyMove"),!1},Wn.dragend=t=>(t.inputState.draggedContent=null,!1),Wn.drop=(t,e)=>{if(!e.dataTransfer)return!1;if(t.state.readOnly)return!0;let i=e.dataTransfer.files;if(i&&i.length){let n=Array(i.length),s=0,r=()=>{++s==i.length&&Un(t,e,n.filter((t=>null!=t)).join(t.state.lineBreak),!1)};for(let t=0;t<i.length;t++){let e=new FileReader;e.onerror=r,e.onload=()=>{/[\x00-\x08\x0e-\x1f]{2}/.test(e.result)||(n[t]=e.result),r()},e.readAsText(i[t])}return!0}{let i=e.dataTransfer.getData("Text");if(i)return Un(t,e,i,!0),!0}return!1},Wn.paste=(t,e)=>{if(t.state.readOnly)return!0;t.observer.flush();let i=jn?null:e.clipboardData;return i?(Dn(t,i.getData("text/plain")||i.getData("text/uri-text")),!0):(function(t){let e=t.dom.parentNode;if(!e)return;let i=e.appendChild(document.createElement("textarea"));i.style.cssText="position: fixed; left: -10000px; top: 10px",i.focus(),setTimeout((()=>{t.focus(),i.remove(),Dn(t,i.value)}),50)}(t),!1)};let Hn=null;Wn.copy=Wn.cut=(t,e)=>{let{text:i,ranges:n,linewise:s}=function(t){let e=[],i=[],n=!1;for(let n of t.selection.ranges)n.empty||(e.push(t.sliceDoc(n.from,n.to)),i.push(n));if(!e.length){let s=-1;for(let{from:n}of t.selection.ranges){let r=t.doc.lineAt(n);r.number>s&&(e.push(r.text),i.push({from:r.from,to:Math.min(t.doc.length,r.to+1)})),s=r.number}n=!0}return{text:e.join(t.lineBreak),ranges:i,linewise:n}}(t.state);if(!i&&!s)return!1;Hn=s?i:null,"cut"!=e.type||t.state.readOnly||t.dispatch({changes:n,scrollIntoView:!0,userEvent:"delete.cut"});let r=jn?null:e.clipboardData;return r?(r.clearData(),r.setData("text/plain",i),!0):(function(t,e){let i=t.dom.parentNode;if(!i)return;let n=i.appendChild(document.createElement("textarea"));n.style.cssText="position: fixed; left: -10000px; top: 10px",n.value=e,n.focus(),n.selectionEnd=e.length,n.selectionStart=0,setTimeout((()=>{n.remove(),t.focus()}),50)}(t,i),!1)};const Fn=ct.define();function Jn(t,e){let i=[];for(let n of t.facet(Ei)){let s=n(t,e);s&&i.push(s)}return i?t.update({effects:i,annotations:Fn.of(!0)}):null}function Kn(t){setTimeout((()=>{let e=t.hasFocus;if(e!=t.inputState.notifiedFocused){let i=Jn(t.state,e);i?t.dispatch(i):t.update([])}}),10)}Mn.focus=t=>{t.inputState.lastFocusTime=Date.now(),t.scrollDOM.scrollTop||!t.inputState.lastScrollTop&&!t.inputState.lastScrollLeft||(t.scrollDOM.scrollTop=t.inputState.lastScrollTop,t.scrollDOM.scrollLeft=t.inputState.lastScrollLeft),Kn(t)},Mn.blur=t=>{t.observer.clearSelectionRange(),Kn(t)},Mn.compositionstart=Mn.compositionupdate=t=>{null==t.inputState.compositionFirstChange&&(t.inputState.compositionFirstChange=!0),t.inputState.composing<0&&(t.inputState.composing=0)},Mn.compositionend=t=>{t.inputState.composing=-1,t.inputState.compositionEndedAt=Date.now(),t.inputState.compositionPendingKey=!0,t.inputState.compositionPendingChange=t.observer.pendingRecords().length>0,t.inputState.compositionFirstChange=null,_e.chrome&&_e.android?t.observer.flushSoon():t.inputState.compositionPendingChange?Promise.resolve().then((()=>t.observer.flush())):setTimeout((()=>{t.inputState.composing<0&&t.docView.hasComposition&&t.update([])}),50)},Mn.contextmenu=t=>{t.inputState.lastContextMenu=Date.now()},Wn.beforeinput=(t,e)=>{var i;let n;if(_e.chrome&&_e.android&&(n=Tn.find((t=>t.inputType==e.inputType)))&&(t.observer.delayAndroidKey(n.key,n.keyCode),"Backspace"==n.key||"Delete"==n.key)){let e=(null===(i=window.visualViewport)||void 0===i?void 0:i.height)||0;setTimeout((()=>{var i;((null===(i=window.visualViewport)||void 0===i?void 0:i.height)||0)>e+10&&t.hasFocus&&(t.contentDOM.blur(),t.focus())}),100)}return!1};const ts=new Set;const es=["pre-wrap","normal","pre-line","break-spaces"];class is{constructor(t){this.lineWrapping=t,this.doc=e.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30,this.heightChanged=!1}heightForGap(t,e){let i=this.doc.lineAt(e).number-this.doc.lineAt(t).number+1;return this.lineWrapping&&(i+=Math.max(0,Math.ceil((e-t-i*this.lineLength*.5)/this.lineLength))),this.lineHeight*i}heightForLine(t){if(!this.lineWrapping)return this.lineHeight;return(1+Math.max(0,Math.ceil((t-this.lineLength)/(this.lineLength-5))))*this.lineHeight}setDoc(t){return this.doc=t,this}mustRefreshForWrapping(t){return es.indexOf(t)>-1!=this.lineWrapping}mustRefreshForHeights(t){let e=!1;for(let i=0;i<t.length;i++){let n=t[i];n<0?i++:this.heightSamples[Math.floor(10*n)]||(e=!0,this.heightSamples[Math.floor(10*n)]=!0)}return e}refresh(t,e,i,n,s,r){let o=es.indexOf(t)>-1,a=Math.round(e)!=Math.round(this.lineHeight)||this.lineWrapping!=o;if(this.lineWrapping=o,this.lineHeight=e,this.charWidth=i,this.textHeight=n,this.lineLength=s,a){this.heightSamples={};for(let t=0;t<r.length;t++){let e=r[t];e<0?t++:this.heightSamples[Math.floor(10*e)]=!0}}return a}}class ns{constructor(t,e){this.from=t,this.heights=e,this.index=0}get more(){return this.index<this.heights.length}}class ss{constructor(t,e,i,n,s){this.from=t,this.length=e,this.top=i,this.height=n,this._content=s}get type(){return"number"==typeof this._content?ni.Text:Array.isArray(this._content)?this._content:this._content.type}get to(){return this.from+this.length}get bottom(){return this.top+this.height}get widget(){return this._content instanceof ai?this._content.widget:null}get widgetLineBreaks(){return"number"==typeof this._content?this._content:0}join(t){let e=(Array.isArray(this._content)?this._content:[this]).concat(Array.isArray(t._content)?t._content:[t]);return new ss(this.from,this.length+t.length,this.top,this.height+t.height,e)}}var rs=function(t){return t[t.ByPos=0]="ByPos",t[t.ByHeight=1]="ByHeight",t[t.ByPosNoHeight=2]="ByPosNoHeight",t}(rs||(rs={}));const os=.001;class as{constructor(t,e,i=2){this.length=t,this.height=e,this.flags=i}get outdated(){return(2&this.flags)>0}set outdated(t){this.flags=(t?2:0)|-3&this.flags}setHeight(t,e){this.height!=e&&(Math.abs(this.height-e)>os&&(t.heightChanged=!0),this.height=e)}replace(t,e,i){return as.of(i)}decomposeLeft(t,e){e.push(this)}decomposeRight(t,e){e.push(this)}applyChanges(t,e,i,n){let s=this,r=i.doc;for(let o=n.length-1;o>=0;o--){let{fromA:a,toA:l,fromB:h,toB:c}=n[o],f=s.lineAt(a,rs.ByPosNoHeight,i.setDoc(e),0,0),u=f.to>=l?f:s.lineAt(l,rs.ByPosNoHeight,i,0,0);for(c+=u.to-l,l=u.to;o>0&&f.from<=n[o-1].toA;)a=n[o-1].fromA,h=n[o-1].fromB,o--,a<f.from&&(f=s.lineAt(a,rs.ByPosNoHeight,i,0,0));h+=f.from-a,a=f.from;let d=ds.build(i.setDoc(r),t,h,c);s=s.replace(a,l,d)}return s.updateHeight(i,0)}static empty(){return new hs(0,0)}static of(t){if(1==t.length)return t[0];let e=0,i=t.length,n=0,s=0;for(;;)if(e==i)if(n>2*s){let s=t[e-1];s.break?t.splice(--e,1,s.left,null,s.right):t.splice(--e,1,s.left,s.right),i+=1+s.break,n-=s.size}else{if(!(s>2*n))break;{let e=t[i];e.break?t.splice(i,1,e.left,null,e.right):t.splice(i,1,e.left,e.right),i+=2+e.break,s-=e.size}}else if(n<s){let i=t[e++];i&&(n+=i.size)}else{let e=t[--i];e&&(s+=e.size)}let r=0;return null==t[e-1]?(r=1,e--):null==t[e]&&(r=1,i++),new fs(as.of(t.slice(0,e)),r,as.of(t.slice(i)))}}as.prototype.size=1;class ls extends as{constructor(t,e,i){super(t,e),this.deco=i}blockAt(t,e,i,n){return new ss(n,this.length,i,this.height,this.deco||0)}lineAt(t,e,i,n,s){return this.blockAt(0,i,n,s)}forEachLine(t,e,i,n,s,r){t<=s+this.length&&e>=s&&r(this.blockAt(0,i,n,s))}updateHeight(t,e=0,i=!1,n){return n&&n.from<=e&&n.more&&this.setHeight(t,n.heights[n.index++]),this.outdated=!1,this}toString(){return`block(${this.length})`}}class hs extends ls{constructor(t,e){super(t,e,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0}blockAt(t,e,i,n){return new ss(n,this.length,i,this.height,this.breaks)}replace(t,e,i){let n=i[0];return 1==i.length&&(n instanceof hs||n instanceof cs&&4&n.flags)&&Math.abs(this.length-n.length)<10?(n instanceof cs?n=new hs(n.length,this.height):n.height=this.height,this.outdated||(n.outdated=!1),n):as.of(i)}updateHeight(t,e=0,i=!1,n){return n&&n.from<=e&&n.more?this.setHeight(t,n.heights[n.index++]):(i||this.outdated)&&this.setHeight(t,Math.max(this.widgetHeight,t.heightForLine(this.length-this.collapsed))+this.breaks*t.lineHeight),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}}class cs extends as{constructor(t){super(t,0)}heightMetrics(t,e){let i,n=t.doc.lineAt(e).number,s=t.doc.lineAt(e+this.length).number,r=s-n+1,o=0;if(t.lineWrapping){let e=Math.min(this.height,t.lineHeight*r);i=e/r,this.length>r+1&&(o=(this.height-e)/(this.length-r-1))}else i=this.height/r;return{firstLine:n,lastLine:s,perLine:i,perChar:o}}blockAt(t,e,i,n){let{firstLine:s,lastLine:r,perLine:o,perChar:a}=this.heightMetrics(e,n);if(e.lineWrapping){let s=n+Math.round(Math.max(0,Math.min(1,(t-i)/this.height))*this.length),r=e.doc.lineAt(s),l=o+r.length*a,h=Math.max(i,t-l/2);return new ss(r.from,r.length,h,l,0)}{let n=Math.max(0,Math.min(r-s,Math.floor((t-i)/o))),{from:a,length:l}=e.doc.line(s+n);return new ss(a,l,i+o*n,o,0)}}lineAt(t,e,i,n,s){if(e==rs.ByHeight)return this.blockAt(t,i,n,s);if(e==rs.ByPosNoHeight){let{from:e,to:n}=i.doc.lineAt(t);return new ss(e,n-e,0,0,0)}let{firstLine:r,perLine:o,perChar:a}=this.heightMetrics(i,s),l=i.doc.lineAt(t),h=o+l.length*a,c=l.number-r,f=n+o*c+a*(l.from-s-c);return new ss(l.from,l.length,Math.max(n,Math.min(f,n+this.height-h)),h,0)}forEachLine(t,e,i,n,s,r){t=Math.max(t,s),e=Math.min(e,s+this.length);let{firstLine:o,perLine:a,perChar:l}=this.heightMetrics(i,s);for(let h=t,c=n;h<=e;){let e=i.doc.lineAt(h);if(h==t){let i=e.number-o;c+=a*i+l*(t-s-i)}let n=a+l*e.length;r(new ss(e.from,e.length,c,n,0)),c+=n,h=e.to+1}}replace(t,e,i){let n=this.length-e;if(n>0){let t=i[i.length-1];t instanceof cs?i[i.length-1]=new cs(t.length+n):i.push(null,new cs(n-1))}if(t>0){let e=i[0];e instanceof cs?i[0]=new cs(t+e.length):i.unshift(new cs(t-1),null)}return as.of(i)}decomposeLeft(t,e){e.push(new cs(t-1),null)}decomposeRight(t,e){e.push(null,new cs(this.length-t-1))}updateHeight(t,e=0,i=!1,n){let s=e+this.length;if(n&&n.from<=e+this.length&&n.more){let i=[],r=Math.max(e,n.from),o=-1;for(n.from>e&&i.push(new cs(n.from-e-1).updateHeight(t,e));r<=s&&n.more;){let e=t.doc.lineAt(r).length;i.length&&i.push(null);let s=n.heights[n.index++];-1==o?o=s:Math.abs(s-o)>=os&&(o=-2);let a=new hs(e,s);a.outdated=!1,i.push(a),r+=e+1}r<=s&&i.push(null,new cs(s-r).updateHeight(t,r));let a=as.of(i);return(o<0||Math.abs(a.height-this.height)>=os||Math.abs(o-this.heightMetrics(t,e).perLine)>=os)&&(t.heightChanged=!0),a}return(i||this.outdated)&&(this.setHeight(t,t.heightForGap(e,e+this.length)),this.outdated=!1),this}toString(){return`gap(${this.length})`}}class fs extends as{constructor(t,e,i){super(t.length+e+i.length,t.height+i.height,e|(t.outdated||i.outdated?2:0)),this.left=t,this.right=i,this.size=t.size+i.size}get break(){return 1&this.flags}blockAt(t,e,i,n){let s=i+this.left.height;return t<s?this.left.blockAt(t,e,i,n):this.right.blockAt(t,e,s,n+this.left.length+this.break)}lineAt(t,e,i,n,s){let r=n+this.left.height,o=s+this.left.length+this.break,a=e==rs.ByHeight?t<r:t<o,l=a?this.left.lineAt(t,e,i,n,s):this.right.lineAt(t,e,i,r,o);if(this.break||(a?l.to<o:l.from>o))return l;let h=e==rs.ByPosNoHeight?rs.ByPosNoHeight:rs.ByPos;return a?l.join(this.right.lineAt(o,h,i,r,o)):this.left.lineAt(o,h,i,n,s).join(l)}forEachLine(t,e,i,n,s,r){let o=n+this.left.height,a=s+this.left.length+this.break;if(this.break)t<a&&this.left.forEachLine(t,e,i,n,s,r),e>=a&&this.right.forEachLine(t,e,i,o,a,r);else{let l=this.lineAt(a,rs.ByPos,i,n,s);t<l.from&&this.left.forEachLine(t,l.from-1,i,n,s,r),l.to>=t&&l.from<=e&&r(l),e>l.to&&this.right.forEachLine(l.to+1,e,i,o,a,r)}}replace(t,e,i){let n=this.left.length+this.break;if(e<n)return this.balanced(this.left.replace(t,e,i),this.right);if(t>this.left.length)return this.balanced(this.left,this.right.replace(t-n,e-n,i));let s=[];t>0&&this.decomposeLeft(t,s);let r=s.length;for(let t of i)s.push(t);if(t>0&&us(s,r-1),e<this.length){let t=s.length;this.decomposeRight(e,s),us(s,t)}return as.of(s)}decomposeLeft(t,e){let i=this.left.length;if(t<=i)return this.left.decomposeLeft(t,e);e.push(this.left),this.break&&(i++,t>=i&&e.push(null)),t>i&&this.right.decomposeLeft(t-i,e)}decomposeRight(t,e){let i=this.left.length,n=i+this.break;if(t>=n)return this.right.decomposeRight(t-n,e);t<i&&this.left.decomposeRight(t,e),this.break&&t<n&&e.push(null),e.push(this.right)}balanced(t,e){return t.size>2*e.size||e.size>2*t.size?as.of(this.break?[t,null,e]:[t,e]):(this.left=t,this.right=e,this.height=t.height+e.height,this.outdated=t.outdated||e.outdated,this.size=t.size+e.size,this.length=t.length+this.break+e.length,this)}updateHeight(t,e=0,i=!1,n){let{left:s,right:r}=this,o=e+s.length+this.break,a=null;return n&&n.from<=e+s.length&&n.more?a=s=s.updateHeight(t,e,i,n):s.updateHeight(t,e,i),n&&n.from<=o+r.length&&n.more?a=r=r.updateHeight(t,o,i,n):r.updateHeight(t,o,i),a?this.balanced(s,r):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}}function us(t,e){let i,n;null==t[e]&&(i=t[e-1])instanceof cs&&(n=t[e+1])instanceof cs&&t.splice(e-1,3,new cs(i.length+1+n.length))}class ds{constructor(t,e){this.pos=t,this.oracle=e,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=t}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(t,e){if(this.lineStart>-1){let t=Math.min(e,this.lineEnd),i=this.nodes[this.nodes.length-1];i instanceof hs?i.length+=t-this.pos:(t>this.pos||!this.isCovered)&&this.nodes.push(new hs(t-this.pos,-1)),this.writtenTo=t,e>t&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=e}point(t,e,i){if(t<e||i.heightRelevant){let n=i.widget?i.widget.estimatedHeight:0,s=i.widget?i.widget.lineBreaks:0;n<0&&(n=this.oracle.lineHeight);let r=e-t;i.block?this.addBlock(new ls(r,n,i)):(r||s||n>=5)&&this.addLineDeco(n,s,r)}else e>t&&this.span(t,e);this.lineEnd>-1&&this.lineEnd<this.pos&&(this.lineEnd=this.oracle.doc.lineAt(this.pos).to)}enterLine(){if(this.lineStart>-1)return;let{from:t,to:e}=this.oracle.doc.lineAt(this.pos);this.lineStart=t,this.lineEnd=e,this.writtenTo<t&&((this.writtenTo<t-1||null==this.nodes[this.nodes.length-1])&&this.nodes.push(this.blankContent(this.writtenTo,t-1)),this.nodes.push(null)),this.pos>t&&this.nodes.push(new hs(this.pos-t,-1)),this.writtenTo=this.pos}blankContent(t,e){let i=new cs(e-t);return this.oracle.doc.lineAt(t).to==e&&(i.flags|=4),i}ensureLine(){this.enterLine();let t=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(t instanceof hs)return t;let e=new hs(0,-1);return this.nodes.push(e),e}addBlock(t){this.enterLine();let e=t.deco;e&&e.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(t),this.writtenTo=this.pos=this.pos+t.length,e&&e.endSide>0&&(this.covering=t)}addLineDeco(t,e,i){let n=this.ensureLine();n.length+=i,n.collapsed+=i,n.widgetHeight=Math.max(n.widgetHeight,t),n.breaks+=e,this.writtenTo=this.pos=this.pos+i}finish(t){let e=0==this.nodes.length?null:this.nodes[this.nodes.length-1];!(this.lineStart>-1)||e instanceof hs||this.isCovered?(this.writtenTo<this.pos||null==e)&&this.nodes.push(this.blankContent(this.writtenTo,this.pos)):this.nodes.push(new hs(0,-1));let i=t;for(let t of this.nodes)t instanceof hs&&t.updateHeight(this.oracle,i),i+=t?t.length:1;return this.nodes}static build(t,e,i,n){let s=new ds(i,t);return At.spans(e,i,n,s,0),s.finish(i)}}class ps{constructor(){this.changes=[]}compareRange(){}comparePoint(t,e,i,n){(t<e||i&&i.heightRelevant||n&&n.heightRelevant)&&hi(t,e,this.changes,5)}}function Os(t,e){let i=t.getBoundingClientRect(),n=t.ownerDocument,s=n.defaultView||window,r=Math.max(0,i.left),o=Math.min(s.innerWidth,i.right),a=Math.max(0,i.top),l=Math.min(s.innerHeight,i.bottom);for(let e=t.parentNode;e&&e!=n.body;)if(1==e.nodeType){let i=e,n=window.getComputedStyle(i);if((i.scrollHeight>i.clientHeight||i.scrollWidth>i.clientWidth)&&"visible"!=n.overflow){let n=i.getBoundingClientRect();r=Math.max(r,n.left),o=Math.min(o,n.right),a=Math.max(a,n.top),l=e==t.parentNode?n.bottom:Math.min(l,n.bottom)}e="absolute"==n.position||"fixed"==n.position?i.offsetParent:i.parentNode}else{if(11!=e.nodeType)break;e=e.host}return{left:r-i.left,right:Math.max(r,o)-i.left,top:a-(i.top+e),bottom:Math.max(a,l)-(i.top+e)}}function gs(t,e){let i=t.getBoundingClientRect();return{left:0,right:i.right-i.left,top:e,bottom:i.bottom-(i.top+e)}}class ms{constructor(t,e,i){this.from=t,this.to=e,this.size=i}static same(t,e){if(t.length!=e.length)return!1;for(let i=0;i<t.length;i++){let n=t[i],s=e[i];if(n.from!=s.from||n.to!=s.to||n.size!=s.size)return!1}return!0}draw(t,e){return si.replace({widget:new ws(this.size*(e?t.scaleY:t.scaleX),e)}).range(this.from,this.to)}}class ws extends ii{constructor(t,e){super(),this.size=t,this.vertical=e}eq(t){return t.size==this.size&&t.vertical==this.vertical}toDOM(){let t=document.createElement("div");return this.vertical?t.style.height=this.size+"px":(t.style.width=this.size+"px",t.style.height="2px",t.style.display="inline-block"),t}get estimatedHeight(){return this.vertical?this.size:-1}}class vs{constructor(t){this.state=t,this.pixelViewport={left:0,right:window.innerWidth,top:0,bottom:0},this.inView=!0,this.paddingTop=0,this.paddingBottom=0,this.contentDOMWidth=0,this.contentDOMHeight=0,this.editorHeight=0,this.editorWidth=0,this.scrollTop=0,this.scrolledToBottom=!0,this.scaleX=1,this.scaleY=1,this.scrollAnchorPos=0,this.scrollAnchorHeight=-1,this.scaler=ks,this.scrollTarget=null,this.printing=!1,this.mustMeasureContent=!0,this.defaultTextDirection=di.LTR,this.visibleRanges=[],this.mustEnforceCursorAssoc=!1;let i=t.facet(Fi).some((t=>"function"!=typeof t&&"cm-lineWrapping"==t.class));this.heightOracle=new is(i),this.stateDeco=t.facet(Ji).filter((t=>"function"!=typeof t)),this.heightMap=as.empty().applyChanges(this.stateDeco,e.empty,this.heightOracle.setDoc(t.doc),[new an(0,0,0,t.doc.length)]),this.viewport=this.getViewport(0,null),this.updateViewportLines(),this.updateForViewport(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=si.set(this.lineGaps.map((t=>t.draw(this,!1)))),this.computeVisibleRanges()}updateForViewport(){let t=[this.viewport],{main:e}=this.state.selection;for(let i=0;i<=1;i++){let n=i?e.head:e.anchor;if(!t.some((({from:t,to:e})=>n>=t&&n<=e))){let{from:e,to:i}=this.lineBlockAt(n);t.push(new bs(e,i))}}this.viewports=t.sort(((t,e)=>t.from-e.from)),this.scaler=this.heightMap.height<=7e6?ks:new Qs(this.heightOracle,this.heightMap,this.viewports)}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,(t=>{this.viewportLines.push(1==this.scaler.scale?t:$s(t,this.scaler))}))}update(t,e=null){this.state=t.state;let i=this.stateDeco;this.stateDeco=this.state.facet(Ji).filter((t=>"function"!=typeof t));let n=t.changedRanges,s=an.extendWithRanges(n,function(t,e,i){let n=new ps;return At.compare(t,e,i,n,0),n.changes}(i,this.stateDeco,t?t.changes:$.empty(this.state.doc.length))),r=this.heightMap.height,o=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollTop);this.heightMap=this.heightMap.applyChanges(this.stateDeco,t.startState.doc,this.heightOracle.setDoc(this.state.doc),s),this.heightMap.height!=r&&(t.flags|=2),o?(this.scrollAnchorPos=t.changes.mapPos(o.from,-1),this.scrollAnchorHeight=o.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=this.heightMap.height);let a=s.length?this.mapViewport(this.viewport,t.changes):this.viewport;(e&&(e.range.head<a.from||e.range.head>a.to)||!this.viewportIsAppropriate(a))&&(a=this.getViewport(0,e));let l=!t.changes.empty||2&t.flags||a.from!=this.viewport.from||a.to!=this.viewport.to;this.viewport=a,this.updateForViewport(),l&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,t.changes))),t.flags|=this.computeVisibleRanges(),e&&(this.scrollTarget=e),!this.mustEnforceCursorAssoc&&t.selectionSet&&t.view.lineWrapping&&t.state.selection.main.empty&&t.state.selection.main.assoc&&!t.state.facet(_i)&&(this.mustEnforceCursorAssoc=!0)}measure(t){let i=t.contentDOM,n=window.getComputedStyle(i),s=this.heightOracle,r=n.whiteSpace;this.defaultTextDirection="rtl"==n.direction?di.RTL:di.LTR;let o=this.heightOracle.mustRefreshForWrapping(r),a=i.getBoundingClientRect(),l=o||this.mustMeasureContent||this.contentDOMHeight!=a.height;this.contentDOMHeight=a.height,this.mustMeasureContent=!1;let h=0,c=0;if(a.width&&a.height){let{scaleX:t,scaleY:e}=pe(i,a);this.scaleX==t&&this.scaleY==e||(this.scaleX=t,this.scaleY=e,h|=8,o=l=!0)}let f=(parseInt(n.paddingTop)||0)*this.scaleY,u=(parseInt(n.paddingBottom)||0)*this.scaleY;this.paddingTop==f&&this.paddingBottom==u||(this.paddingTop=f,this.paddingBottom=u,h|=10),this.editorWidth!=t.scrollDOM.clientWidth&&(s.lineWrapping&&(l=!0),this.editorWidth=t.scrollDOM.clientWidth,h|=8);let d=t.scrollDOM.scrollTop*this.scaleY;this.scrollTop!=d&&(this.scrollAnchorHeight=-1,this.scrollTop=d),this.scrolledToBottom=Se(t.scrollDOM);let p=(this.printing?gs:Os)(i,this.paddingTop),O=p.top-this.pixelViewport.top,g=p.bottom-this.pixelViewport.bottom;this.pixelViewport=p;let m=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(m!=this.inView&&(this.inView=m,m&&(l=!0)),!this.inView&&!this.scrollTarget)return 0;let w=a.width;if(this.contentDOMWidth==w&&this.editorHeight==t.scrollDOM.clientHeight||(this.contentDOMWidth=a.width,this.editorHeight=t.scrollDOM.clientHeight,h|=8),l){let i=t.docView.measureVisibleLineHeights(this.viewport);if(s.mustRefreshForHeights(i)&&(o=!0),o||s.lineWrapping&&Math.abs(w-this.contentDOMWidth)>s.charWidth){let{lineHeight:e,charWidth:n,textHeight:a}=t.docView.measureTextSize();o=e>0&&s.refresh(r,e,n,a,w/n,i),o&&(t.docView.minWidth=0,h|=8)}O>0&&g>0?c=Math.max(O,g):O<0&&g<0&&(c=Math.min(O,g)),s.heightChanged=!1;for(let n of this.viewports){let r=n.from==this.viewport.from?i:t.docView.measureVisibleLineHeights(n);this.heightMap=(o?as.empty().applyChanges(this.stateDeco,e.empty,this.heightOracle,[new an(0,0,0,t.state.doc.length)]):this.heightMap).updateHeight(s,0,o,new ns(n.from,r))}s.heightChanged&&(h|=2)}let v=!this.viewportIsAppropriate(this.viewport,c)||this.scrollTarget&&(this.scrollTarget.range.head<this.viewport.from||this.scrollTarget.range.head>this.viewport.to);return v&&(this.viewport=this.getViewport(c,this.scrollTarget)),this.updateForViewport(),(2&h||v)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(o?[]:this.lineGaps,t)),h|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,t.docView.enforceCursorAssoc()),h}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(t,e){let i=.5-Math.max(-.5,Math.min(.5,t/1e3/2)),n=this.heightMap,s=this.heightOracle,{visibleTop:r,visibleBottom:o}=this,a=new bs(n.lineAt(r-1e3*i,rs.ByHeight,s,0,0).from,n.lineAt(o+1e3*(1-i),rs.ByHeight,s,0,0).to);if(e){let{head:t}=e.range;if(t<a.from||t>a.to){let i,r=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),o=n.lineAt(t,rs.ByPos,s,0,0);i="center"==e.y?(o.top+o.bottom)/2-r/2:"start"==e.y||"nearest"==e.y&&t<a.from?o.top:o.bottom-r,a=new bs(n.lineAt(i-500,rs.ByHeight,s,0,0).from,n.lineAt(i+r+500,rs.ByHeight,s,0,0).to)}}return a}mapViewport(t,e){let i=e.mapPos(t.from,-1),n=e.mapPos(t.to,1);return new bs(this.heightMap.lineAt(i,rs.ByPos,this.heightOracle,0,0).from,this.heightMap.lineAt(n,rs.ByPos,this.heightOracle,0,0).to)}viewportIsAppropriate({from:t,to:e},i=0){if(!this.inView)return!0;let{top:n}=this.heightMap.lineAt(t,rs.ByPos,this.heightOracle,0,0),{bottom:s}=this.heightMap.lineAt(e,rs.ByPos,this.heightOracle,0,0),{visibleTop:r,visibleBottom:o}=this;return(0==t||n<=r-Math.max(10,Math.min(-i,250)))&&(e==this.state.doc.length||s>=o+Math.max(10,Math.min(i,250)))&&n>r-2e3&&s<o+2e3}mapLineGaps(t,e){if(!t.length||e.empty)return t;let i=[];for(let n of t)e.touchesRange(n.from,n.to)||i.push(new ms(e.mapPos(n.from),e.mapPos(n.to),n.size));return i}ensureLineGaps(t,e){let i=this.heightOracle.lineWrapping,n=i?1e4:2e3,s=n>>1,r=n<<1;if(this.defaultTextDirection!=di.LTR&&!i)return[];let o=[],a=(n,r,l,h)=>{if(r-n<s)return;let c=this.state.selection.main,f=[c.from];c.empty||f.push(c.to);for(let t of f)if(t>n&&t<r)return a(n,t-10,l,h),void a(t+10,r,l,h);let u=function(t,e){for(let i of t)if(e(i))return i;return}(t,(t=>t.from>=l.from&&t.to<=l.to&&Math.abs(t.from-n)<s&&Math.abs(t.to-r)<s&&!f.some((e=>t.from<e&&t.to>e))));if(!u){if(r<l.to&&e&&i&&e.visibleRanges.some((t=>t.from<=r&&t.to>=r))){let t=e.moveToLineBoundary(Y.cursor(r),!1,!0).head;t>n&&(r=t)}u=new ms(n,r,this.gapSize(l,n,r,h))}o.push(u)};for(let t of this.viewportLines){if(t.length<r)continue;let e=ys(t.from,t.to,this.stateDeco);if(e.total<r)continue;let s,o,l=this.scrollTarget?this.scrollTarget.range.head:null;if(i){let i,r,a=n/this.heightOracle.lineLength*this.heightOracle.lineHeight;if(null!=l){let n=xs(e,l),s=((this.visibleBottom-this.visibleTop)/2+a)/t.height;i=n-s,r=n+s}else i=(this.visibleTop-t.top-a)/t.height,r=(this.visibleBottom-t.top+a)/t.height;s=Ss(e,i),o=Ss(e,r)}else{let t,i,r=e.total*this.heightOracle.charWidth,a=n*this.heightOracle.charWidth;if(null!=l){let n=xs(e,l),s=((this.pixelViewport.right-this.pixelViewport.left)/2+a)/r;t=n-s,i=n+s}else t=(this.pixelViewport.left-a)/r,i=(this.pixelViewport.right+a)/r;s=Ss(e,t),o=Ss(e,i)}s>t.from&&a(t.from,s,t,e),o<t.to&&a(o,t.to,t,e)}return o}gapSize(t,e,i,n){let s=xs(n,i)-xs(n,e);return this.heightOracle.lineWrapping?t.height*s:n.total*this.heightOracle.charWidth*s}updateLineGaps(t){ms.same(t,this.lineGaps)||(this.lineGaps=t,this.lineGapDeco=si.set(t.map((t=>t.draw(this,this.heightOracle.lineWrapping)))))}computeVisibleRanges(){let t=this.stateDeco;this.lineGaps.length&&(t=t.concat(this.lineGapDeco));let e=[];At.spans(t,this.viewport.from,this.viewport.to,{span(t,i){e.push({from:t,to:i})},point(){}},20);let i=e.length!=this.visibleRanges.length||this.visibleRanges.some(((t,i)=>t.from!=e[i].from||t.to!=e[i].to));return this.visibleRanges=e,i?4:0}lineBlockAt(t){return t>=this.viewport.from&&t<=this.viewport.to&&this.viewportLines.find((e=>e.from<=t&&e.to>=t))||$s(this.heightMap.lineAt(t,rs.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(t){return $s(this.heightMap.lineAt(this.scaler.fromDOM(t),rs.ByHeight,this.heightOracle,0,0),this.scaler)}scrollAnchorAt(t){let e=this.lineBlockAtHeight(t+8);return e.from>=this.viewport.from||this.viewportLines[0].top-t>200?e:this.viewportLines[0]}elementAtHeight(t){return $s(this.heightMap.blockAt(this.scaler.fromDOM(t),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}}class bs{constructor(t,e){this.from=t,this.to=e}}function ys(t,e,i){let n=[],s=t,r=0;return At.spans(i,t,e,{span(){},point(t,e){t>s&&(n.push({from:s,to:t}),r+=t-s),s=e}},20),s<e&&(n.push({from:s,to:e}),r+=e-s),{total:r,ranges:n}}function Ss({total:t,ranges:e},i){if(i<=0)return e[0].from;if(i>=1)return e[e.length-1].to;let n=Math.floor(t*i);for(let t=0;;t++){let{from:i,to:s}=e[t],r=s-i;if(n<=r)return i+n;n-=r}}function xs(t,e){let i=0;for(let{from:n,to:s}of t.ranges){if(e<=s){i+=e-n;break}i+=s-n}return i/t.total}const ks={toDOM:t=>t,fromDOM:t=>t,scale:1};class Qs{constructor(t,e,i){let n=0,s=0,r=0;this.viewports=i.map((({from:i,to:s})=>{let r=e.lineAt(i,rs.ByPos,t,0,0).top,o=e.lineAt(s,rs.ByPos,t,0,0).bottom;return n+=o-r,{from:i,to:s,top:r,bottom:o,domTop:0,domBottom:0}})),this.scale=(7e6-n)/(e.height-n);for(let t of this.viewports)t.domTop=r+(t.top-s)*this.scale,r=t.domBottom=t.domTop+(t.bottom-t.top),s=t.bottom}toDOM(t){for(let e=0,i=0,n=0;;e++){let s=e<this.viewports.length?this.viewports[e]:null;if(!s||t<s.top)return n+(t-i)*this.scale;if(t<=s.bottom)return s.domTop+(t-s.top);i=s.bottom,n=s.domBottom}}fromDOM(t){for(let e=0,i=0,n=0;;e++){let s=e<this.viewports.length?this.viewports[e]:null;if(!s||t<s.domTop)return i+(t-n)/this.scale;if(t<=s.domBottom)return s.top+(t-s.domTop);i=s.bottom,n=s.domBottom}}}function $s(t,e){if(1==e.scale)return t;let i=e.toDOM(t.top),n=e.toDOM(t.bottom);return new ss(t.from,t.length,i,n-i,Array.isArray(t._content)?t._content.map((t=>$s(t,e))):t._content)}const Ps=j.define({combine:t=>t.join(" ")}),Zs=j.define({combine:t=>t.indexOf(!0)>-1}),Cs=Ut.newName(),Ts=Ut.newName(),As=Ut.newName(),Rs={"&light":"."+Ts,"&dark":"."+As};function Xs(t,e,i){return new Ut(e,{finish:e=>/&/.test(e)?e.replace(/&\w*/,(e=>{if("&"==e)return t;if(!i||!i[e])throw new RangeError(`Unsupported selector: ${e}`);return i[e]})):t+" "+e})}const Ys=Xs("."+Cs,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",minHeight:"100%",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 6px"},".cm-layer":{position:"absolute",left:0,top:0,contain:"size style","& > *":{position:"absolute"}},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{pointerEvents:"none"},"&.cm-focused > .cm-scroller > .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#444"},".cm-dropCursor":{position:"absolute"},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:"block"},".cm-iso":{unicodeBidi:"isolate"},".cm-announced":{position:"fixed",top:"-10000px"},"@media print":{".cm-announced":{display:"none"}},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",insetInlineStart:0,zIndex:200},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",borderRight:"1px solid #ddd"},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top"},".cm-highlightSpace:before":{content:"attr(data-display)",position:"absolute",pointerEvents:"none",color:"#888"},".cm-highlightTab":{backgroundImage:'url(\'data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="200" height="20"><path stroke="%23888" stroke-width="1" fill="none" d="M1 10H196L190 5M190 15L196 10M197 4L197 16"/></svg>\')',backgroundSize:"auto 100%",backgroundPosition:"right 90%",backgroundRepeat:"no-repeat"},".cm-trailingSpace":{backgroundColor:"#ff332255"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},Rs),Ws="￿";class Ms{constructor(t,e){this.points=t,this.text="",this.lineSeparator=e.facet(Qt.lineSeparator)}append(t){this.text+=t}lineBreak(){this.text+=Ws}readRange(t,e){if(!t)return this;let i=t.parentNode;for(let n=t;;){this.findPointBefore(i,n);let t=this.text.length;this.readNode(n);let s=n.nextSibling;if(s==e)break;let r=Qe.get(n),o=Qe.get(s);(r&&o?r.breakAfter:(r?r.breakAfter:Ds(n))||Ds(s)&&("BR"!=n.nodeName||n.cmIgnore)&&this.text.length>t)&&this.lineBreak(),n=s}return this.findPointBefore(i,e),this}readTextNode(t){let e=t.nodeValue;for(let i of this.points)i.node==t&&(i.pos=this.text.length+Math.min(i.offset,e.length));for(let i=0,n=this.lineSeparator?null:/\r\n?|\n/g;;){let s,r=-1,o=1;if(this.lineSeparator?(r=e.indexOf(this.lineSeparator,i),o=this.lineSeparator.length):(s=n.exec(e))&&(r=s.index,o=s[0].length),this.append(e.slice(i,r<0?e.length:r)),r<0)break;if(this.lineBreak(),o>1)for(let e of this.points)e.node==t&&e.pos>this.text.length&&(e.pos-=o-1);i=r+o}}readNode(t){if(t.cmIgnore)return;let e=Qe.get(t),i=e&&e.overrideDOMText;if(null!=i){this.findPointInside(t,i.length);for(let t=i.iter();!t.next().done;)t.lineBreak?this.lineBreak():this.append(t.value)}else 3==t.nodeType?this.readTextNode(t):"BR"==t.nodeName?t.nextSibling&&this.lineBreak():1==t.nodeType&&this.readRange(t.firstChild,null)}findPointBefore(t,e){for(let i of this.points)i.node==t&&t.childNodes[i.offset]==e&&(i.pos=this.text.length)}findPointInside(t,e){for(let i of this.points)(3==t.nodeType?i.node==t:t.contains(i.node))&&(i.pos=this.text.length+(js(t,i.node,i.offset)?e:0))}}function js(t,e,i){for(;;){if(!e||i<fe(e))return!1;if(e==t)return!0;i=he(e)+1,e=e.parentNode}}function Ds(t){return 1==t.nodeType&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(t.nodeName)}class Es{constructor(t,e){this.node=t,this.offset=e,this.pos=-1}}class qs{constructor(t,e,i,n){this.typeOver=n,this.bounds=null,this.text="";let{impreciseHead:s,impreciseAnchor:r}=t.docView;if(t.state.readOnly&&e>-1)this.newSel=null;else if(e>-1&&(this.bounds=t.docView.domBoundsAround(e,i,0))){let e=s||r?[]:function(t){let e=[];if(t.root.activeElement!=t.contentDOM)return e;let{anchorNode:i,anchorOffset:n,focusNode:s,focusOffset:r}=t.observer.selectionRange;i&&(e.push(new Es(i,n)),s==i&&r==n||e.push(new Es(s,r)));return e}(t),i=new Ms(e,t.state);i.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=i.text,this.newSel=function(t,e){if(0==t.length)return null;let i=t[0].pos,n=2==t.length?t[1].pos:i;return i>-1&&n>-1?Y.single(i+e,n+e):null}(e,this.bounds.from)}else{let e=t.observer.selectionRange,i=s&&s.node==e.focusNode&&s.offset==e.focusOffset||!re(t.contentDOM,e.focusNode)?t.state.selection.main.head:t.docView.posFromDOM(e.focusNode,e.focusOffset),n=r&&r.node==e.anchorNode&&r.offset==e.anchorOffset||!re(t.contentDOM,e.anchorNode)?t.state.selection.main.anchor:t.docView.posFromDOM(e.anchorNode,e.anchorOffset),o=t.viewport;if(_e.ios&&t.state.selection.main.empty&&i!=n&&(o.from>0||o.to<t.state.doc.length)){let e=o.from-Math.min(i,n),s=o.to-Math.max(i,n);0!=e&&1!=e||0!=s&&-1!=s||(i=0,n=t.state.doc.length)}this.newSel=Y.single(n,i)}}}function _s(t,i){let n,{newSel:s}=i,r=t.state.selection.main,o=t.inputState.lastKeyTime>Date.now()-100?t.inputState.lastKeyCode:-1;if(i.bounds){let{from:s,to:a}=i.bounds,l=r.from,h=null;(8===o||_e.android&&i.text.length<a-s)&&(l=r.to,h="end");let c=function(t,e,i,n){let s=Math.min(t.length,e.length),r=0;for(;r<s&&t.charCodeAt(r)==e.charCodeAt(r);)r++;if(r==s&&t.length==e.length)return null;let o=t.length,a=e.length;for(;o>0&&a>0&&t.charCodeAt(o-1)==e.charCodeAt(a-1);)o--,a--;if("end"==n){i-=o+Math.max(0,r-Math.min(o,a))-r}if(o<r&&t.length<e.length){r-=i<=r&&i>=o?r-i:0,a=r+(a-o),o=r}else if(a<r){r-=i<=r&&i>=a?r-i:0,o=r+(o-a),a=r}return{from:r,toA:o,toB:a}}(t.state.doc.sliceString(s,a,Ws),i.text,l-s,h);c&&(_e.chrome&&13==o&&c.toB==c.from+2&&i.text.slice(c.from,c.toB)==Ws+Ws&&c.toB--,n={from:s+c.from,to:s+c.toA,insert:e.of(i.text.slice(c.from,c.toB).split(Ws))})}else s&&(!t.hasFocus&&t.state.facet(Bi)||s.main.eq(r))&&(s=null);if(!n&&!s)return!1;if(!n&&i.typeOver&&!r.empty&&s&&s.main.empty?n={from:r.from,to:r.to,insert:t.state.doc.slice(r.from,r.to)}:n&&n.from>=r.from&&n.to<=r.to&&(n.from!=r.from||n.to!=r.to)&&r.to-r.from-(n.to-n.from)<=4?n={from:r.from,to:r.to,insert:t.state.doc.slice(r.from,n.from).append(n.insert).append(t.state.doc.slice(n.to,r.to))}:(_e.mac||_e.android)&&n&&n.from==n.to&&n.from==r.head-1&&/^\. ?$/.test(n.insert.toString())&&"off"==t.contentDOM.getAttribute("autocorrect")?(s&&2==n.insert.length&&(s=Y.single(s.main.anchor-1,s.main.head-1)),n={from:r.from,to:r.to,insert:e.of([" "])}):_e.chrome&&n&&n.from==n.to&&n.from==r.head&&"\n "==n.insert.toString()&&t.lineWrapping&&(s&&(s=Y.single(s.main.anchor-1,s.main.head-1)),n={from:r.from,to:r.to,insert:e.of([" "])}),n){if(_e.ios&&t.inputState.flushIOSKey())return!0;if(_e.android&&(n.from==r.from&&n.to==r.to&&1==n.insert.length&&2==n.insert.lines&&be(t.contentDOM,"Enter",13)||(n.from==r.from-1&&n.to==r.to&&0==n.insert.length||8==o&&n.insert.length<n.to-n.from&&n.to>r.head)&&be(t.contentDOM,"Backspace",8)||n.from==r.from&&n.to==r.to+1&&0==n.insert.length&&be(t.contentDOM,"Delete",46)))return!0;let e,i=n.insert.toString();t.inputState.composing>=0&&t.inputState.composing++;let a=()=>e||(e=function(t,e,i){let n,s=t.state,r=s.selection.main;if(e.from>=r.from&&e.to<=r.to&&e.to-e.from>=(r.to-r.from)/3&&(!i||i.main.empty&&i.main.from==e.from+e.insert.length)&&t.inputState.composing<0){let i=r.from<e.from?s.sliceDoc(r.from,e.from):"",o=r.to>e.to?s.sliceDoc(e.to,r.to):"";n=s.replaceSelection(t.state.toText(i+e.insert.sliceString(0,void 0,t.state.lineBreak)+o))}else{let o=s.changes(e),a=i&&i.main.to<=o.newLength?i.main:void 0;if(s.selection.ranges.length>1&&t.inputState.composing>=0&&e.to<=r.to&&e.to>=r.to-10){let l,h=t.state.sliceDoc(e.from,e.to),c=i&&fn(t,i.main.head);if(c){let t=e.insert.length-(e.to-e.from);l={from:c.from,to:c.to-t}}else l=t.state.doc.lineAt(r.head);let f=r.to-e.to,u=r.to-r.from;n=s.changeByRange((i=>{if(i.from==r.from&&i.to==r.to)return{changes:o,range:a||i.map(o)};let n=i.to-f,c=n-h.length;if(i.to-i.from!=u||t.state.sliceDoc(c,n)!=h||i.to>=l.from&&i.from<=l.to)return{range:i};let d=s.changes({from:c,to:n,insert:e.insert}),p=i.to-r.to;return{changes:d,range:a?Y.range(Math.max(0,a.anchor+p),Math.max(0,a.head+p)):i.map(d)}}))}else n={changes:o,selection:a&&s.selection.replaceRange(a)}}let o="input.type";(t.composing||t.inputState.compositionPendingChange&&t.inputState.compositionEndedAt>Date.now()-50)&&(t.inputState.compositionPendingChange=!1,o+=".compose",t.inputState.compositionFirstChange&&(o+=".start",t.inputState.compositionFirstChange=!1));return s.update(n,{userEvent:o,scrollIntoView:!0})}(t,n,s));return t.state.facet(Di).some((e=>e(t,n.from,n.to,i,a)))||t.dispatch(a()),!0}if(s&&!s.main.eq(r)){let e=!1,i="select";return t.inputState.lastSelectionTime>Date.now()-50&&("select"==t.inputState.lastSelectionOrigin&&(e=!0),i=t.inputState.lastSelectionOrigin),t.dispatch({selection:s,scrollIntoView:e,userEvent:i}),!0}return!1}const Vs={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},Is=_e.ie&&_e.ie_version<=11;class zs{constructor(t){this.view=t,this.active=!1,this.selectionRange=new Oe,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.parentCheck=-1,this.dom=t.contentDOM,this.observer=new MutationObserver((e=>{for(let t of e)this.queue.push(t);(_e.ie&&_e.ie_version<=11||_e.ios&&t.composing)&&e.some((t=>"childList"==t.type&&t.removedNodes.length||"characterData"==t.type&&t.oldValue.length>t.target.nodeValue.length))?this.flushSoon():this.flush()})),Is&&(this.onCharData=t=>{this.queue.push({target:t.target,type:"characterData",oldValue:t.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),"function"==typeof ResizeObserver&&(this.resizeScroll=new ResizeObserver((()=>{var t;(null===(t=this.view.docView)||void 0===t?void 0:t.lastUpdate)<Date.now()-75&&this.onResize()})),this.resizeScroll.observe(t.scrollDOM)),this.addWindowListeners(this.win=t.win),this.start(),"function"==typeof IntersectionObserver&&(this.intersection=new IntersectionObserver((t=>{this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),t.length>0&&t[t.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))}),{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver((t=>{t.length>0&&t[t.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))}),{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(t){this.view.inputState.runHandlers("scroll",t),this.intersecting&&this.view.measure()}onScroll(t){this.intersecting&&this.flush(!1),this.onScrollChanged(t)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout((()=>{this.resizeTimeout=-1,this.view.requestMeasure()}),50))}onPrint(){this.view.viewState.printing=!0,this.view.measure(),setTimeout((()=>{this.view.viewState.printing=!1,this.view.requestMeasure()}),500)}updateGaps(t){if(this.gapIntersection&&(t.length!=this.gaps.length||this.gaps.some(((e,i)=>e!=t[i])))){this.gapIntersection.disconnect();for(let e of t)this.gapIntersection.observe(e);this.gaps=t}}onSelectionChange(t){let e=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view:i}=this,n=this.selectionRange;if(i.state.facet(Bi)?i.root.activeElement!=this.dom:!oe(i.dom,n))return;let s=n.anchorNode&&i.docView.nearest(n.anchorNode);s&&s.ignoreEvent(t)?e||(this.selectionChanged=!1):(_e.ie&&_e.ie_version<=11||_e.android&&_e.chrome)&&!i.state.selection.main.empty&&n.focusNode&&le(n.focusNode,n.focusOffset,n.anchorNode,n.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:t}=this,e=_e.safari&&11==t.root.nodeType&&function(t){let e=t.activeElement;for(;e&&e.shadowRoot;)e=e.shadowRoot.activeElement;return e}(this.dom.ownerDocument)==this.dom&&function(t){let e=null;function i(t){t.preventDefault(),t.stopImmediatePropagation(),e=t.getTargetRanges()[0]}if(t.contentDOM.addEventListener("beforeinput",i,!0),t.dom.ownerDocument.execCommand("indent"),t.contentDOM.removeEventListener("beforeinput",i,!0),!e)return null;let n=e.startContainer,s=e.startOffset,r=e.endContainer,o=e.endOffset,a=t.docView.domAtPos(t.state.selection.main.anchor);le(a.node,a.offset,r,o)&&([n,s,r,o]=[r,o,n,s]);return{anchorNode:n,anchorOffset:s,focusNode:r,focusOffset:o}}(this.view)||se(t.root);if(!e||this.selectionRange.eq(e))return!1;let i=oe(this.dom,e);return i&&!this.selectionChanged&&t.inputState.lastFocusTime>Date.now()-200&&t.inputState.lastTouchTime<Date.now()-300&&function(t,e){let i=e.focusNode,n=e.focusOffset;if(!i||e.anchorNode!=i||e.anchorOffset!=n)return!1;for(n=Math.min(n,fe(i));;)if(n){if(1!=i.nodeType)return!1;let t=i.childNodes[n-1];"false"==t.contentEditable?n--:(i=t,n=fe(i))}else{if(i==t)return!0;n=he(i),i=i.parentNode}}(this.dom,e)?(this.view.inputState.lastFocusTime=0,t.docView.updateSelection(),!1):(this.selectionRange.setRange(e),i&&(this.selectionChanged=!0),!0)}setSelectionRange(t,e){this.selectionRange.set(t.node,t.offset,e.node,e.offset),this.selectionChanged=!1}clearSelectionRange(){this.selectionRange.set(null,0,null,0)}listenForScroll(){this.parentCheck=-1;let t=0,e=null;for(let i=this.dom;i;)if(1==i.nodeType)!e&&t<this.scrollTargets.length&&this.scrollTargets[t]==i?t++:e||(e=this.scrollTargets.slice(0,t)),e&&e.push(i),i=i.assignedSlot||i.parentNode;else{if(11!=i.nodeType)break;i=i.host}if(t<this.scrollTargets.length&&!e&&(e=this.scrollTargets.slice(0,t)),e){for(let t of this.scrollTargets)t.removeEventListener("scroll",this.onScroll);for(let t of this.scrollTargets=e)t.addEventListener("scroll",this.onScroll)}}ignore(t){if(!this.active)return t();try{return this.stop(),t()}finally{this.start(),this.clear()}}start(){this.active||(this.observer.observe(this.dom,Vs),Is&&this.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.active=!0)}stop(){this.active&&(this.active=!1,this.observer.disconnect(),Is&&this.dom.removeEventListener("DOMCharacterDataModified",this.onCharData))}clear(){this.processRecords(),this.queue.length=0,this.selectionChanged=!1}delayAndroidKey(t,e){var i;if(!this.delayedAndroidKey){let t=()=>{let t=this.delayedAndroidKey;if(t){this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=t.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&t.force&&be(this.dom,t.key,t.keyCode)}};this.flushingAndroidKey=this.view.win.requestAnimationFrame(t)}this.delayedAndroidKey&&"Enter"!=t||(this.delayedAndroidKey={key:t,keyCode:e,force:this.lastChange<Date.now()-50||!!(null===(i=this.delayedAndroidKey)||void 0===i?void 0:i.force)})}clearDelayedAndroidKey(){this.win.cancelAnimationFrame(this.flushingAndroidKey),this.delayedAndroidKey=null,this.flushingAndroidKey=-1}flushSoon(){this.delayedFlush<0&&(this.delayedFlush=this.view.win.requestAnimationFrame((()=>{this.delayedFlush=-1,this.flush()})))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}pendingRecords(){for(let t of this.observer.takeRecords())this.queue.push(t);return this.queue}processRecords(){let t=this.pendingRecords();t.length&&(this.queue=[]);let e=-1,i=-1,n=!1;for(let s of t){let t=this.readMutation(s);t&&(t.typeOver&&(n=!0),-1==e?({from:e,to:i}=t):(e=Math.min(t.from,e),i=Math.max(t.to,i)))}return{from:e,to:i,typeOver:n}}readChange(){let{from:t,to:e,typeOver:i}=this.processRecords(),n=this.selectionChanged&&oe(this.dom,this.selectionRange);if(t<0&&!n)return null;t>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let s=new qs(this.view,t,e,i);return this.view.docView.domChanged={newSel:s.newSel?s.newSel.main:null},s}flush(t=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;t&&this.readSelectionRange();let e=this.readChange();if(!e)return this.view.requestMeasure(),!1;let i=this.view.state,n=_s(this.view,e);return this.view.state==i&&this.view.update([]),n}readMutation(t){let e=this.view.docView.nearest(t.target);if(!e||e.ignoreMutation(t))return null;if(e.markDirty("attributes"==t.type),"attributes"==t.type&&(e.flags|=4),"childList"==t.type){let i=Bs(e,t.previousSibling||t.target.previousSibling,-1),n=Bs(e,t.nextSibling||t.target.nextSibling,1);return{from:i?e.posAfter(i):e.posAtStart,to:n?e.posBefore(n):e.posAtEnd,typeOver:!1}}return"characterData"==t.type?{from:e.posAtStart,to:e.posAtEnd,typeOver:t.target.nodeValue==t.oldValue}:null}setWindow(t){t!=this.win&&(this.removeWindowListeners(this.win),this.win=t,this.addWindowListeners(this.win))}addWindowListeners(t){t.addEventListener("resize",this.onResize),t.addEventListener("beforeprint",this.onPrint),t.addEventListener("scroll",this.onScroll),t.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(t){t.removeEventListener("scroll",this.onScroll),t.removeEventListener("resize",this.onResize),t.removeEventListener("beforeprint",this.onPrint),t.document.removeEventListener("selectionchange",this.onSelectionChange)}destroy(){var t,e,i;this.stop(),null===(t=this.intersection)||void 0===t||t.disconnect(),null===(e=this.gapIntersection)||void 0===e||e.disconnect(),null===(i=this.resizeScroll)||void 0===i||i.disconnect();for(let t of this.scrollTargets)t.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey)}}function Bs(t,e,i){for(;e;){let n=Qe.get(e);if(n&&n.parent==t)return n;let s=e.parentNode;e=s!=t.dom?s:i>0?e.nextSibling:e.previousSibling}return null}class Gs{get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return this.inputState.composing>0}get compositionStarted(){return this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(t={}){this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.className="cm-announced",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),t.parent&&t.parent.appendChild(this.dom);let{dispatch:e}=t;this.dispatchTransactions=t.dispatchTransactions||e&&(t=>t.forEach((t=>e(t,this))))||(t=>this.update(t)),this.dispatch=this.dispatch.bind(this),this._root=t.root||function(t){for(;t;){if(t&&(9==t.nodeType||11==t.nodeType&&t.host))return t;t=t.assignedSlot||t.parentNode}return null}(t.parent)||document,this.viewState=new vs(t.state||Qt.create(t)),t.scrollTo&&t.scrollTo.is(Ii)&&(this.viewState.scrollTarget=t.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(Li).map((t=>new Ui(t)));for(let t of this.plugins)t.update(this);this.observer=new zs(this),this.inputState=new Pn(this),this.inputState.ensureHandlers(this.plugins),this.docView=new hn(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure()}dispatch(...t){let e=1==t.length&&t[0]instanceof pt?t:1==t.length&&Array.isArray(t[0])?t[0]:[this.state.update(...t)];this.dispatchTransactions(e,this)}update(t){if(0!=this.updateState)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let e,i=!1,n=!1,s=this.state;for(let e of t){if(e.startState!=s)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");s=e.state}if(this.destroyed)return void(this.viewState.state=s);let r=this.hasFocus,o=0,a=null;t.some((t=>t.annotation(Fn)))?(this.inputState.notifiedFocused=r,o=1):r!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=r,a=Jn(s,r),a||(o=1));let l=this.observer.delayedAndroidKey,h=null;if(l?(this.observer.clearDelayedAndroidKey(),h=this.observer.readChange(),(h&&!this.state.doc.eq(s.doc)||!this.state.selection.eq(s.selection))&&(h=null)):this.observer.clear(),s.facet(Qt.phrases)!=this.state.facet(Qt.phrases))return this.setState(s);e=ln.create(this,s,t),e.flags|=o;let c=this.viewState.scrollTarget;try{this.updateState=2;for(let e of t){if(c&&(c=c.map(e.changes)),e.scrollIntoView){let{main:t}=e.state.selection;c=new Vi(t.empty?t:Y.cursor(t.head,t.head>t.anchor?-1:1))}for(let t of e.effects)t.is(Ii)&&(c=t.value.clip(this.state))}this.viewState.update(e,c),this.bidiCache=Us.update(this.bidiCache,e.changes),e.empty||(this.updatePlugins(e),this.inputState.update(e)),i=this.docView.update(e),this.state.facet(on)!=this.styleModules&&this.mountStyles(),n=this.updateAttrs(),this.showAnnouncements(t),this.docView.updateSelection(i,t.some((t=>t.isUserEvent("select.pointer"))))}finally{this.updateState=0}if(e.startState.facet(Ps)!=e.state.facet(Ps)&&(this.viewState.mustMeasureContent=!0),(i||n||c||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),!e.empty)for(let t of this.state.facet(ji))try{t(e)}catch(t){zi(this.state,t,"update listener")}(a||h)&&Promise.resolve().then((()=>{a&&this.state==a.startState&&this.dispatch(a),h&&!_s(this,h)&&l.force&&be(this.contentDOM,l.key,l.keyCode)}))}setState(t){if(0!=this.updateState)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed)return void(this.viewState.state=t);this.updateState=2;let e=this.hasFocus;try{for(let t of this.plugins)t.destroy(this);this.viewState=new vs(t),this.plugins=t.facet(Li).map((t=>new Ui(t))),this.pluginMap.clear();for(let t of this.plugins)t.update(this);this.docView.destroy(),this.docView=new hn(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}e&&this.focus(),this.requestMeasure()}updatePlugins(t){let e=t.startState.facet(Li),i=t.state.facet(Li);if(e!=i){let n=[];for(let s of i){let i=e.indexOf(s);if(i<0)n.push(new Ui(s));else{let e=this.plugins[i];e.mustUpdate=t,n.push(e)}}for(let e of this.plugins)e.mustUpdate!=t&&e.destroy(this);this.plugins=n,this.pluginMap.clear()}else for(let e of this.plugins)e.mustUpdate=t;for(let t=0;t<this.plugins.length;t++)this.plugins[t].update(this);e!=i&&this.inputState.ensureHandlers(this.plugins)}measure(t=!0){if(this.destroyed)return;if(this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey)return this.measureScheduled=-1,void this.requestMeasure();this.measureScheduled=0,t&&this.observer.forceFlush();let e=null,i=this.scrollDOM,n=i.scrollTop*this.scaleY,{scrollAnchorPos:s,scrollAnchorHeight:r}=this.viewState;Math.abs(n-this.viewState.scrollTop)>1&&(r=-1),this.viewState.scrollAnchorHeight=-1;try{for(let t=0;;t++){if(r<0)if(Se(i))s=-1,r=this.viewState.heightMap.height;else{let t=this.viewState.scrollAnchorAt(n);s=t.from,r=t.top}this.updateState=1;let o=this.viewState.measure(this);if(!o&&!this.measureRequests.length&&null==this.viewState.scrollTarget)break;if(t>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let a=[];4&o||([this.measureRequests,a]=[a,this.measureRequests]);let l=a.map((t=>{try{return t.read(this)}catch(t){return zi(this.state,t),Ns}})),h=ln.create(this,this.state,[]),c=!1;h.flags|=o,e?e.flags|=o:e=h,this.updateState=2,h.empty||(this.updatePlugins(h),this.inputState.update(h),this.updateAttrs(),c=this.docView.update(h));for(let t=0;t<a.length;t++)if(l[t]!=Ns)try{let e=a[t];e.write&&e.write(l[t],this)}catch(t){zi(this.state,t)}if(c&&this.docView.updateSelection(!0),!h.viewportChanged&&0==this.measureRequests.length){if(this.viewState.editorHeight){if(this.viewState.scrollTarget){this.docView.scrollIntoView(this.viewState.scrollTarget),this.viewState.scrollTarget=null,r=-1;continue}{let t=(s<0?this.viewState.heightMap.height:this.viewState.lineBlockAt(s).top)-r;if(t>1||t<-1){n+=t,i.scrollTop=n/this.scaleY,r=-1;continue}}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(e&&!e.empty)for(let t of this.state.facet(ji))t(e)}get themeClasses(){return Cs+" "+(this.state.facet(Zs)?As:Ts)+" "+this.state.facet(Ps)}updateAttrs(){let t=Hs(this,Hi,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),e={spellcheck:"false",autocorrect:"off",autocapitalize:"off",translate:"no",contenteditable:this.state.facet(Bi)?"true":"false",class:"cm-content",style:`${_e.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(e["aria-readonly"]="true"),Hs(this,Fi,e);let i=this.observer.ignore((()=>{let i=Je(this.contentDOM,this.contentAttrs,e),n=Je(this.dom,this.editorAttrs,t);return i||n}));return this.editorAttrs=t,this.contentAttrs=e,i}showAnnouncements(t){let e=!0;for(let i of t)for(let t of i.effects)if(t.is(Gs.announce)){e&&(this.announceDOM.textContent=""),e=!1,this.announceDOM.appendChild(document.createElement("div")).textContent=t.value}}mountStyles(){this.styleModules=this.state.facet(on);let t=this.state.facet(Gs.cspNonce);Ut.mount(this.root,this.styleModules.concat(Ys).reverse(),t?{nonce:t}:void 0)}readMeasured(){if(2==this.updateState)throw new Error("Reading the editor layout isn't allowed during an update");0==this.updateState&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(t){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame((()=>this.measure()))),t){if(this.measureRequests.indexOf(t)>-1)return;if(null!=t.key)for(let e=0;e<this.measureRequests.length;e++)if(this.measureRequests[e].key===t.key)return void(this.measureRequests[e]=t);this.measureRequests.push(t)}}plugin(t){let e=this.pluginMap.get(t);return(void 0===e||e&&e.spec!=t)&&this.pluginMap.set(t,e=this.plugins.find((e=>e.spec==t))||null),e&&e.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(t){return this.readMeasured(),this.viewState.elementAtHeight(t)}lineBlockAtHeight(t){return this.readMeasured(),this.viewState.lineBlockAtHeight(t)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(t){return this.viewState.lineBlockAt(t)}get contentHeight(){return this.viewState.contentHeight}moveByChar(t,e,i){return $n(this,t,kn(this,t,e,i))}moveByGroup(t,e){return $n(this,t,kn(this,t,e,(e=>function(t,e,i){let n=t.state.charCategorizer(e),s=n(i);return t=>{let e=n(t);return s==yt.Space&&(s=e),s==e}}(this,t.head,e))))}visualLineSide(t,e){let i=this.bidiSpans(t),n=this.textDirectionAt(t.from),s=i[e?i.length-1:0];return Y.cursor(s.side(e,n)+t.from,s.forward(!e,n)?1:-1)}moveToLineBoundary(t,e,i=!0){return function(t,e,i,n){let s=xn(t,e.head),r=n&&s.type==ni.Text&&(t.lineWrapping||s.widgetLineBreaks)?t.coordsAtPos(e.assoc<0&&e.head>s.from?e.head-1:e.head):null;if(r){let e=t.dom.getBoundingClientRect(),n=t.textDirectionAt(s.from),o=t.posAtCoords({x:i==(n==di.LTR)?e.right-1:e.left+1,y:(r.top+r.bottom)/2});if(null!=o)return Y.cursor(o,i?-1:1)}return Y.cursor(i?s.to:s.from,i?-1:1)}(this,t,e,i)}moveVertically(t,e,i){return $n(this,t,function(t,e,i,n){let s=e.head,r=i?1:-1;if(s==(i?t.state.doc.length:0))return Y.cursor(s,e.assoc);let o,a=e.goalColumn,l=t.contentDOM.getBoundingClientRect(),h=t.coordsAtPos(s,e.assoc||-1),c=t.documentTop;if(h)null==a&&(a=h.left-l.left),o=r<0?h.top:h.bottom;else{let e=t.viewState.lineBlockAt(s);null==a&&(a=Math.min(l.right-l.left,t.defaultCharacterWidth*(s-e.from))),o=(r<0?e.top:e.bottom)+c}let f=l.left+a,u=null!=n?n:t.viewState.heightOracle.textHeight>>1;for(let e=0;;e+=10){let i=o+(u+e)*r,n=yn(t,{x:f,y:i},!1,r);if(i<l.top||i>l.bottom||(r<0?n<s:n>s)){let e=t.docView.coordsForChar(n),s=!e||i<e.top?-1:1;return Y.cursor(n,s,void 0,a)}}}(this,t,e,i))}domAtPos(t){return this.docView.domAtPos(t)}posAtDOM(t,e=0){return this.docView.posFromDOM(t,e)}posAtCoords(t,e=!0){return this.readMeasured(),yn(this,t,e)}coordsAtPos(t,e=1){this.readMeasured();let i=this.docView.coordsAt(t,e);if(!i||i.left==i.right)return i;let n=this.state.doc.lineAt(t),s=this.bidiSpans(n);return ue(i,s[xi.find(s,t-n.from,-1,e)].dir==di.LTR==e>0)}coordsForChar(t){return this.readMeasured(),this.docView.coordsForChar(t)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(t){return!this.state.facet(qi)||t<this.viewport.from||t>this.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(t))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(t){if(t.length>Ls)return Ci(t.length);let e,i=this.textDirectionAt(t.from);for(let n of this.bidiCache)if(n.from==t.from&&n.dir==i&&(n.fresh||ki(n.isolates,e=nn(this,t))))return n.order;e||(e=nn(this,t));let n=Zi(t.text,i,e);return this.bidiCache.push(new Us(t.from,t.to,i,e,!0,n)),n}get hasFocus(){var t;return(this.dom.ownerDocument.hasFocus()||_e.safari&&(null===(t=this.inputState)||void 0===t?void 0:t.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore((()=>{we(this.contentDOM),this.docView.updateSelection()}))}setRoot(t){this._root!=t&&(this._root=t,this.observer.setWindow((9==t.nodeType?t:t.ownerDocument).defaultView||window),this.mountStyles())}destroy(){for(let t of this.plugins)t.destroy(this);this.plugins=[],this.inputState.destroy(),this.docView.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(t,e={}){return Ii.of(new Vi("number"==typeof t?Y.cursor(t):t,e.y,e.x,e.yMargin,e.xMargin))}scrollSnapshot(){let{scrollTop:t,scrollLeft:e}=this.scrollDOM,i=this.viewState.scrollAnchorAt(t);return Ii.of(new Vi(Y.cursor(i.from),"start","start",i.top-t,e,!0))}static domEventHandlers(t){return Ni.define((()=>({})),{eventHandlers:t})}static domEventObservers(t){return Ni.define((()=>({})),{eventObservers:t})}static theme(t,e){let i=Ut.newName(),n=[Ps.of(i),on.of(Xs(`.${i}`,t))];return e&&e.dark&&n.push(Zs.of(!0)),n}static baseTheme(t){return H.lowest(on.of(Xs("."+Cs,t,Rs)))}static findFromDOM(t){var e;let i=t.querySelector(".cm-content"),n=i&&Qe.get(i)||Qe.get(t);return(null===(e=null==n?void 0:n.rootView)||void 0===e?void 0:e.view)||null}}Gs.styleModule=on,Gs.inputHandler=Di,Gs.focusChangeEffect=Ei,Gs.perLineTextDirection=qi,Gs.exceptionSink=Mi,Gs.updateListener=ji,Gs.editable=Bi,Gs.mouseSelectionStyle=Wi,Gs.dragMovesSelection=Yi,Gs.clickAddsSelectionRange=Xi,Gs.decorations=Ji,Gs.outerDecorations=Ki,Gs.atomicRanges=tn,Gs.bidiIsolatedRanges=en,Gs.scrollMargins=sn,Gs.darkTheme=Zs,Gs.cspNonce=j.define({combine:t=>t.length?t[0]:""}),Gs.contentAttributes=Fi,Gs.editorAttributes=Hi,Gs.lineWrapping=Gs.contentAttributes.of({class:"cm-lineWrapping"}),Gs.announce=dt.define();const Ls=4096,Ns={};class Us{constructor(t,e,i,n,s,r){this.from=t,this.to=e,this.dir=i,this.isolates=n,this.fresh=s,this.order=r}static update(t,e){if(e.empty&&!t.some((t=>t.fresh)))return t;let i=[],n=t.length?t[t.length-1].dir:di.LTR;for(let s=Math.max(0,t.length-10);s<t.length;s++){let r=t[s];r.dir!=n||e.touchesRange(r.from,r.to)||i.push(new Us(e.mapPos(r.from,1),e.mapPos(r.to,-1),r.dir,r.isolates,!1,r.order))}return i}}function Hs(t,e,i){for(let n=t.state.facet(e),s=n.length-1;s>=0;s--){let e=n[s],r="function"==typeof e?e(t):e;r&&Ue(r,i)}return i}const Fs=_e.mac?"mac":_e.windows?"win":_e.linux?"linux":"key";function Js(t,e,i){return e.altKey&&(t="Alt-"+t),e.ctrlKey&&(t="Ctrl-"+t),e.metaKey&&(t="Meta-"+t),!1!==i&&e.shiftKey&&(t="Shift-"+t),t}const Ks=H.default(Gs.domEventHandlers({keydown:(t,e)=>or(ir(e.state),t,e,"editor")})),tr=j.define({enables:Ks}),er=new WeakMap;function ir(t){let e=t.facet(tr),i=er.get(e);return i||er.set(e,i=function(t,e=Fs){let i=Object.create(null),n=Object.create(null),s=(t,e)=>{let i=n[t];if(null==i)n[t]=e;else if(i!=e)throw new Error("Key binding "+t+" is used both as a regular binding and as a multi-stroke prefix")},r=(t,n,r,o,a)=>{var l,h;let c=i[t]||(i[t]=Object.create(null)),f=n.split(/ (?!$)/).map((t=>function(t,e){const i=t.split(/-(?!$)/);let n,s,r,o,a=i[i.length-1];"Space"==a&&(a=" ");for(let t=0;t<i.length-1;++t){const a=i[t];if(/^(cmd|meta|m)$/i.test(a))o=!0;else if(/^a(lt)?$/i.test(a))n=!0;else if(/^(c|ctrl|control)$/i.test(a))s=!0;else if(/^s(hift)?$/i.test(a))r=!0;else{if(!/^mod$/i.test(a))throw new Error("Unrecognized modifier name: "+a);"mac"==e?o=!0:s=!0}}return n&&(a="Alt-"+a),s&&(a="Ctrl-"+a),o&&(a="Meta-"+a),r&&(a="Shift-"+a),a}(t,e)));for(let e=1;e<f.length;e++){let i=f.slice(0,e).join(" ");s(i,!0),c[i]||(c[i]={preventDefault:!0,stopPropagation:!1,run:[e=>{let n=sr={view:e,prefix:i,scope:t};return setTimeout((()=>{sr==n&&(sr=null)}),rr),!0}]})}let u=f.join(" ");s(u,!1);let d=c[u]||(c[u]={preventDefault:!1,stopPropagation:!1,run:(null===(h=null===(l=c._any)||void 0===l?void 0:l.run)||void 0===h?void 0:h.slice())||[]});r&&d.run.push(r),o&&(d.preventDefault=!0),a&&(d.stopPropagation=!0)};for(let n of t){let t=n.scope?n.scope.split(" "):["editor"];if(n.any)for(let e of t){let t=i[e]||(i[e]=Object.create(null));t._any||(t._any={preventDefault:!1,stopPropagation:!1,run:[]});for(let e in t)t[e].run.push(n.any)}let s=n[e]||n.key;if(s)for(let e of t)r(e,s,n.run,n.preventDefault,n.stopPropagation),n.shift&&r(e,"Shift-"+s,n.shift,n.preventDefault,n.stopPropagation)}return i}(e.reduce(((t,e)=>t.concat(e)),[]))),i}function nr(t,e,i){return or(ir(t.state),e,t,i)}let sr=null;const rr=4e3;function or(t,e,i,n){let s=function(t){var e=!(te&&t.metaKey&&t.shiftKey&&!t.ctrlKey&&!t.altKey||ee&&t.shiftKey&&t.key&&1==t.key.length||"Unidentified"==t.key)&&t.key||(t.shiftKey?Kt:Jt)[t.keyCode]||t.key||"Unidentified";return"Esc"==e&&(e="Escape"),"Del"==e&&(e="Delete"),"Left"==e&&(e="ArrowLeft"),"Up"==e&&(e="ArrowUp"),"Right"==e&&(e="ArrowRight"),"Down"==e&&(e="ArrowDown"),e}(e),r=S(b(s,0))==s.length&&" "!=s,o="",a=!1,l=!1,h=!1;sr&&sr.view==i&&sr.scope==n&&(o=sr.prefix+" ",Rn.indexOf(e.keyCode)<0&&(l=!0,sr=null));let c,f,u=new Set,d=t=>{if(t){for(let n of t.run)if(!u.has(n)&&(u.add(n),n(i,e)))return t.stopPropagation&&(h=!0),!0;t.preventDefault&&(t.stopPropagation&&(h=!0),l=!0)}return!1},p=t[n];return p&&(d(p[o+Js(s,e,!r)])?a=!0:r&&(e.altKey||e.metaKey||e.ctrlKey)&&!(_e.windows&&e.ctrlKey&&e.altKey)&&(c=Jt[e.keyCode])&&c!=s?(d(p[o+Js(c,e,!0)])||e.shiftKey&&(f=Kt[e.keyCode])!=s&&f!=c&&d(p[o+Js(f,e,!1)]))&&(a=!0):r&&e.shiftKey&&d(p[o+Js(s,e,!0)])&&(a=!0),!a&&d(p._any)&&(a=!0)),l&&(a=!0),a&&h&&e.stopPropagation(),a}class ar{constructor(t,e,i,n,s){this.className=t,this.left=e,this.top=i,this.width=n,this.height=s}draw(){let t=document.createElement("div");return t.className=this.className,this.adjust(t),t}update(t,e){return e.className==this.className&&(this.adjust(t),!0)}adjust(t){t.style.left=this.left+"px",t.style.top=this.top+"px",null!=this.width&&(t.style.width=this.width+"px"),t.style.height=this.height+"px"}eq(t){return this.left==t.left&&this.top==t.top&&this.width==t.width&&this.height==t.height&&this.className==t.className}static forRange(t,e,i){if(i.empty){let n=t.coordsAtPos(i.head,i.assoc||1);if(!n)return[];let s=lr(t);return[new ar(e,n.left-s.left,n.top-s.top,null,n.bottom-n.top)]}return function(t,e,i){if(i.to<=t.viewport.from||i.from>=t.viewport.to)return[];let n=Math.max(i.from,t.viewport.from),s=Math.min(i.to,t.viewport.to),r=t.textDirection==di.LTR,o=t.contentDOM,a=o.getBoundingClientRect(),l=lr(t),h=o.querySelector(".cm-line"),c=h&&window.getComputedStyle(h),f=a.left+(c?parseInt(c.paddingLeft)+Math.min(0,parseInt(c.textIndent)):0),u=a.right-(c?parseInt(c.paddingRight):0),d=xn(t,n),p=xn(t,s),O=d.type==ni.Text?d:null,g=p.type==ni.Text?p:null;O&&(t.lineWrapping||d.widgetLineBreaks)&&(O=hr(t,n,O));g&&(t.lineWrapping||p.widgetLineBreaks)&&(g=hr(t,s,g));if(O&&g&&O.from==g.from)return w(v(i.from,i.to,O));{let e=O?v(i.from,null,O):b(d,!1),n=g?v(null,i.to,g):b(p,!0),s=[];return(O||d).to<(g||p).from-(O&&g?1:0)||d.widgetLineBreaks>1&&e.bottom+t.defaultLineHeight/2<n.top?s.push(m(f,e.bottom,u,n.top)):e.bottom<n.top&&t.elementAtHeight((e.bottom+n.top)/2).type==ni.Text&&(e.bottom=n.top=(e.bottom+n.top)/2),w(e).concat(s).concat(w(n))}function m(t,i,n,s){return new ar(e,t-l.left,i-l.top-.01,n-t,s-i+.01)}function w({top:t,bottom:e,horizontal:i}){let n=[];for(let s=0;s<i.length;s+=2)n.push(m(i[s],t,i[s+1],e));return n}function v(e,i,n){let s=1e9,o=-1e9,a=[];function l(e,i,l,h,c){let d=t.coordsAtPos(e,e==n.to?-2:2),p=t.coordsAtPos(l,l==n.from?2:-2);d&&p&&(s=Math.min(d.top,p.top,s),o=Math.max(d.bottom,p.bottom,o),c==di.LTR?a.push(r&&i?f:d.left,r&&h?u:p.right):a.push(!r&&h?f:p.left,!r&&i?u:d.right))}let h=null!=e?e:n.from,c=null!=i?i:n.to;for(let n of t.visibleRanges)if(n.to>h&&n.from<c)for(let s=Math.max(n.from,h),r=Math.min(n.to,c);;){let n=t.state.doc.lineAt(s);for(let o of t.bidiSpans(n)){let t=o.from+n.from,a=o.to+n.from;if(t>=r)break;a>s&&l(Math.max(t,s),null==e&&t<=h,Math.min(a,r),null==i&&a>=c,o.dir)}if(s=n.to+1,s>=r)break}return 0==a.length&&l(h,null==e,c,null==i,t.textDirection),{top:s,bottom:o,horizontal:a}}function b(t,e){let i=a.top+(e?t.top:t.bottom);return{top:i,bottom:i,horizontal:[]}}}(t,e,i)}}function lr(t){let e=t.scrollDOM.getBoundingClientRect();return{left:(t.textDirection==di.LTR?e.left:e.right-t.scrollDOM.clientWidth*t.scaleX)-t.scrollDOM.scrollLeft*t.scaleX,top:e.top-t.scrollDOM.scrollTop*t.scaleY}}function hr(t,e,i){let n=Y.cursor(e);return{from:Math.max(i.from,t.moveToLineBoundary(n,!1,!0).from),to:Math.min(i.to,t.moveToLineBoundary(n,!0,!0).from),type:ni.Text}}class cr{constructor(t,e){this.view=t,this.layer=e,this.drawn=[],this.scaleX=1,this.scaleY=1,this.measureReq={read:this.measure.bind(this),write:this.draw.bind(this)},this.dom=t.scrollDOM.appendChild(document.createElement("div")),this.dom.classList.add("cm-layer"),e.above&&this.dom.classList.add("cm-layer-above"),e.class&&this.dom.classList.add(e.class),this.scale(),this.dom.setAttribute("aria-hidden","true"),this.setOrder(t.state),t.requestMeasure(this.measureReq),e.mount&&e.mount(this.dom,t)}update(t){t.startState.facet(fr)!=t.state.facet(fr)&&this.setOrder(t.state),(this.layer.update(t,this.dom)||t.geometryChanged)&&(this.scale(),t.view.requestMeasure(this.measureReq))}setOrder(t){let e=0,i=t.facet(fr);for(;e<i.length&&i[e]!=this.layer;)e++;this.dom.style.zIndex=String((this.layer.above?150:-1)-e)}measure(){return this.layer.markers(this.view)}scale(){let{scaleX:t,scaleY:e}=this.view;t==this.scaleX&&e==this.scaleY||(this.scaleX=t,this.scaleY=e,this.dom.style.transform=`scale(${1/t}, ${1/e})`)}draw(t){if(t.length!=this.drawn.length||t.some(((t,e)=>{return i=t,n=this.drawn[e],!(i.constructor==n.constructor&&i.eq(n));var i,n}))){let e=this.dom.firstChild,i=0;for(let n of t)n.update&&e&&n.constructor&&this.drawn[i].constructor&&n.update(e,this.drawn[i])?(e=e.nextSibling,i++):this.dom.insertBefore(n.draw(),e);for(;e;){let t=e.nextSibling;e.remove(),e=t}this.drawn=t}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}}const fr=j.define();function ur(t){return[Ni.define((e=>new cr(e,t))),fr.of(t)]}const dr=!_e.ios,pr=j.define({combine:t=>$t(t,{cursorBlinkRate:1200,drawRangeCursor:!0},{cursorBlinkRate:(t,e)=>Math.min(t,e),drawRangeCursor:(t,e)=>t||e})});function Or(t={}){return[pr.of(t),mr,vr,yr,_i.of(!0)]}function gr(t){return t.startState.facet(pr)!=t.state.facet(pr)}const mr=ur({above:!0,markers(t){let{state:e}=t,i=e.facet(pr),n=[];for(let s of e.selection.ranges){let r=s==e.selection.main;if(s.empty?!r||dr:i.drawRangeCursor){let e=r?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",i=s.empty?s:Y.cursor(s.head,s.head>s.anchor?-1:1);for(let s of ar.forRange(t,e,i))n.push(s)}}return n},update(t,e){t.transactions.some((t=>t.selection))&&(e.style.animationName="cm-blink"==e.style.animationName?"cm-blink2":"cm-blink");let i=gr(t);return i&&wr(t.state,e),t.docChanged||t.selectionSet||i},mount(t,e){wr(e.state,t)},class:"cm-cursorLayer"});function wr(t,e){e.style.animationDuration=t.facet(pr).cursorBlinkRate+"ms"}const vr=ur({above:!1,markers:t=>t.state.selection.ranges.map((e=>e.empty?[]:ar.forRange(t,"cm-selectionBackground",e))).reduce(((t,e)=>t.concat(e))),update:(t,e)=>t.docChanged||t.selectionSet||t.viewportChanged||gr(t),class:"cm-selectionLayer"}),br={".cm-line":{"& ::selection":{backgroundColor:"transparent !important"},"&::selection":{backgroundColor:"transparent !important"}}};dr&&(br[".cm-line"].caretColor="transparent !important",br[".cm-content"]={caretColor:"transparent !important"});const yr=H.highest(Gs.theme(br)),Sr=dt.define({map:(t,e)=>null==t?null:e.mapPos(t)}),xr=z.define({create:()=>null,update:(t,e)=>(null!=t&&(t=e.changes.mapPos(t)),e.effects.reduce(((t,e)=>e.is(Sr)?e.value:t),t))}),kr=Ni.fromClass(class{constructor(t){this.view=t,this.cursor=null,this.measureReq={read:this.readPos.bind(this),write:this.drawCursor.bind(this)}}update(t){var e;let i=t.state.field(xr);null==i?null!=this.cursor&&(null===(e=this.cursor)||void 0===e||e.remove(),this.cursor=null):(this.cursor||(this.cursor=this.view.scrollDOM.appendChild(document.createElement("div")),this.cursor.className="cm-dropCursor"),(t.startState.field(xr)!=i||t.docChanged||t.geometryChanged)&&this.view.requestMeasure(this.measureReq))}readPos(){let{view:t}=this,e=t.state.field(xr),i=null!=e&&t.coordsAtPos(e);if(!i)return null;let n=t.scrollDOM.getBoundingClientRect();return{left:i.left-n.left+t.scrollDOM.scrollLeft*t.scaleX,top:i.top-n.top+t.scrollDOM.scrollTop*t.scaleY,height:i.bottom-i.top}}drawCursor(t){if(this.cursor){let{scaleX:e,scaleY:i}=this.view;t?(this.cursor.style.left=t.left/e+"px",this.cursor.style.top=t.top/i+"px",this.cursor.style.height=t.height/i+"px"):this.cursor.style.left="-100000px"}}destroy(){this.cursor&&this.cursor.remove()}setDropPos(t){this.view.state.field(xr)!=t&&this.view.dispatch({effects:Sr.of(t)})}},{eventObservers:{dragover(t){this.setDropPos(this.view.posAtCoords({x:t.clientX,y:t.clientY}))},dragleave(t){t.target!=this.view.contentDOM&&this.view.contentDOM.contains(t.relatedTarget)||this.setDropPos(null)},dragend(){this.setDropPos(null)},drop(){this.setDropPos(null)}}});function Qr(){return[xr,kr]}function $r(t,e,i,n,s){e.lastIndex=0;for(let r,o=t.iterRange(i,n),a=i;!o.next().done;a+=o.value.length)if(!o.lineBreak)for(;r=e.exec(o.value);)s(a+r.index,r)}class Pr{constructor(t){const{regexp:e,decoration:i,decorate:n,boundary:s,maxLength:r=1e3}=t;if(!e.global)throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");if(this.regexp=e,n)this.addMatch=(t,e,i,s)=>n(s,i,i+t[0].length,t,e);else if("function"==typeof i)this.addMatch=(t,e,n,s)=>{let r=i(t,e,n);r&&s(n,n+t[0].length,r)};else{if(!i)throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");this.addMatch=(t,e,n,s)=>s(n,n+t[0].length,i)}this.boundary=s,this.maxLength=r}createDeco(t){let e=new Rt,i=e.add.bind(e);for(let{from:e,to:n}of function(t,e){let i=t.visibleRanges;if(1==i.length&&i[0].from==t.viewport.from&&i[0].to==t.viewport.to)return i;let n=[];for(let{from:s,to:r}of i)s=Math.max(t.state.doc.lineAt(s).from,s-e),r=Math.min(t.state.doc.lineAt(r).to,r+e),n.length&&n[n.length-1].to>=s?n[n.length-1].to=r:n.push({from:s,to:r});return n}(t,this.maxLength))$r(t.state.doc,this.regexp,e,n,((e,n)=>this.addMatch(n,t,e,i)));return e.finish()}updateDeco(t,e){let i=1e9,n=-1;return t.docChanged&&t.changes.iterChanges(((e,s,r,o)=>{o>t.view.viewport.from&&r<t.view.viewport.to&&(i=Math.min(r,i),n=Math.max(o,n))})),t.viewportChanged||n-i>1e3?this.createDeco(t.view):n>-1?this.updateRange(t.view,e.map(t.changes),i,n):e}updateRange(t,e,i,n){for(let s of t.visibleRanges){let r=Math.max(s.from,i),o=Math.min(s.to,n);if(o>r){let i=t.state.doc.lineAt(r),n=i.to<o?t.state.doc.lineAt(o):i,a=Math.max(s.from,i.from),l=Math.min(s.to,n.to);if(this.boundary){for(;r>i.from;r--)if(this.boundary.test(i.text[r-1-i.from])){a=r;break}for(;o<n.to;o++)if(this.boundary.test(n.text[o-n.from])){l=o;break}}let h,c=[],f=(t,e,i)=>c.push(i.range(t,e));if(i==n)for(this.regexp.lastIndex=a-i.from;(h=this.regexp.exec(i.text))&&h.index<l-i.from;)this.addMatch(h,t,h.index+i.from,f);else $r(t.state.doc,this.regexp,a,l,((e,i)=>this.addMatch(i,t,e,f)));e=e.update({filterFrom:a,filterTo:l,filter:(t,e)=>t<a||e>l,add:c})}}return e}}const Zr=null!=/x/.unicode?"gu":"g",Cr=new RegExp("[\0-\b\n--Ÿ­؜​‎‏\u2028\u2029‭‮⁦⁧⁩\ufeff-]",Zr),Tr={0:"null",7:"bell",8:"backspace",10:"newline",11:"vertical tab",13:"carriage return",27:"escape",8203:"zero width space",8204:"zero width non-joiner",8205:"zero width joiner",8206:"left-to-right mark",8207:"right-to-left mark",8232:"line separator",8237:"left-to-right override",8238:"right-to-left override",8294:"left-to-right isolate",8295:"right-to-left isolate",8297:"pop directional isolate",8233:"paragraph separator",65279:"zero width no-break space",65532:"object replacement"};let Ar=null;const Rr=j.define({combine(t){let e=$t(t,{render:null,specialChars:Cr,addSpecialChars:null});return(e.replaceTabs=!function(){var t;if(null==Ar&&"undefined"!=typeof document&&document.body){let e=document.body.style;Ar=null!=(null!==(t=e.tabSize)&&void 0!==t?t:e.MozTabSize)}return Ar||!1}())&&(e.specialChars=new RegExp("\t|"+e.specialChars.source,Zr)),e.addSpecialChars&&(e.specialChars=new RegExp(e.specialChars.source+"|"+e.addSpecialChars.source,Zr)),e}});function Xr(t={}){return[Rr.of(t),Yr||(Yr=Ni.fromClass(class{constructor(t){this.view=t,this.decorations=si.none,this.decorationCache=Object.create(null),this.decorator=this.makeDecorator(t.state.facet(Rr)),this.decorations=this.decorator.createDeco(t)}makeDecorator(t){return new Pr({regexp:t.specialChars,decoration:(e,i,n)=>{let{doc:s}=i.state,r=b(e[0],0);if(9==r){let t=s.lineAt(n),e=i.state.tabSize,r=It(t.text,e,n-t.from);return si.replace({widget:new Mr((e-r%e)*this.view.defaultCharacterWidth/this.view.scaleX)})}return this.decorationCache[r]||(this.decorationCache[r]=si.replace({widget:new Wr(t,r)}))},boundary:t.replaceTabs?void 0:/[^]/})}update(t){let e=t.state.facet(Rr);t.startState.facet(Rr)!=e?(this.decorator=this.makeDecorator(e),this.decorations=this.decorator.createDeco(t.view)):this.decorations=this.decorator.updateDeco(t,this.decorations)}},{decorations:t=>t.decorations}))]}let Yr=null;class Wr extends ii{constructor(t,e){super(),this.options=t,this.code=e}eq(t){return t.code==this.code}toDOM(t){let e=function(t){return t>=32?"•":10==t?"␤":String.fromCharCode(9216+t)}(this.code),i=t.state.phrase("Control character")+" "+(Tr[this.code]||"0x"+this.code.toString(16)),n=this.options.render&&this.options.render(this.code,i,e);if(n)return n;let s=document.createElement("span");return s.textContent=e,s.title=i,s.setAttribute("aria-label",i),s.className="cm-specialChar",s}ignoreEvent(){return!1}}class Mr extends ii{constructor(t){super(),this.width=t}eq(t){return t.width==this.width}toDOM(){let t=document.createElement("span");return t.textContent="\t",t.className="cm-tab",t.style.width=this.width+"px",t}ignoreEvent(){return!1}}const jr=Ni.fromClass(class{constructor(){this.height=1e3,this.attrs={style:"padding-bottom: 1000px"}}update(t){let{view:e}=t,i=e.viewState.editorHeight*e.scaleY-e.defaultLineHeight-e.documentPadding.top-.5;i>=0&&i!=this.height&&(this.height=i,this.attrs={style:`padding-bottom: ${i}px`})}});function Dr(){return qr}const Er=si.line({class:"cm-activeLine"}),qr=Ni.fromClass(class{constructor(t){this.decorations=this.getDeco(t)}update(t){(t.docChanged||t.selectionSet)&&(this.decorations=this.getDeco(t.view))}getDeco(t){let e=-1,i=[];for(let n of t.state.selection.ranges){let s=t.lineBlockAt(n.head);s.from>e&&(i.push(Er.range(s.from)),e=s.from)}return si.set(i)}},{decorations:t=>t.decorations});class _r extends ii{constructor(t){super(),this.content=t}toDOM(){let t=document.createElement("span");return t.className="cm-placeholder",t.style.pointerEvents="none",t.appendChild("string"==typeof this.content?document.createTextNode(this.content):this.content),"string"==typeof this.content?t.setAttribute("aria-label","placeholder "+this.content):t.setAttribute("aria-hidden","true"),t}coordsAt(t){let e=t.firstChild?ae(t.firstChild):[];if(!e.length)return null;let i=window.getComputedStyle(t.parentNode),n=ue(e[0],"rtl"!=i.direction),s=parseInt(i.lineHeight);return n.bottom-n.top>1.5*s?{left:n.left,right:n.right,top:n.top,bottom:n.top+s}:n}ignoreEvent(){return!1}}const Vr=2e3;function Ir(t,e){let i=t.posAtCoords({x:e.clientX,y:e.clientY},!1),n=t.state.doc.lineAt(i),s=i-n.from,r=s>Vr?-1:s==n.length?function(t,e){let i=t.coordsAtPos(t.viewport.from);return i?Math.round(Math.abs((i.left-e)/t.defaultCharacterWidth)):-1}(t,e.clientX):It(n.text,t.state.tabSize,i-n.from);return{line:n.number,col:r,off:s}}function zr(t,e){let i=Ir(t,e),n=t.state.selection;return i?{update(t){if(t.docChanged){let e=t.changes.mapPos(t.startState.doc.line(i.line).from),s=t.state.doc.lineAt(e);i={line:s.number,col:i.col,off:Math.min(i.off,s.length)},n=n.map(t.changes)}},get(e,s,r){let o=Ir(t,e);if(!o)return n;let a=function(t,e,i){let n=Math.min(e.line,i.line),s=Math.max(e.line,i.line),r=[];if(e.off>Vr||i.off>Vr||e.col<0||i.col<0){let o=Math.min(e.off,i.off),a=Math.max(e.off,i.off);for(let e=n;e<=s;e++){let i=t.doc.line(e);i.length<=a&&r.push(Y.range(i.from+o,i.to+a))}}else{let o=Math.min(e.col,i.col),a=Math.max(e.col,i.col);for(let e=n;e<=s;e++){let i=t.doc.line(e),n=zt(i.text,o,t.tabSize,!0);if(n<0)r.push(Y.cursor(i.to));else{let e=zt(i.text,a,t.tabSize);r.push(Y.range(i.from+n,i.from+e))}}}return r}(t.state,i,o);return a.length?r?Y.create(a.concat(n.ranges)):Y.create(a):n}}:null}function Br(t){let e=(null==t?void 0:t.eventFilter)||(t=>t.altKey&&0==t.button);return Gs.mouseSelectionStyle.of(((t,i)=>e(i)?zr(t,i):null))}const Gr={Alt:[18,t=>!!t.altKey],Control:[17,t=>!!t.ctrlKey],Shift:[16,t=>!!t.shiftKey],Meta:[91,t=>!!t.metaKey]},Lr={style:"cursor: crosshair"};function Nr(t={}){let[e,i]=Gr[t.key||"Alt"],n=Ni.fromClass(class{constructor(t){this.view=t,this.isDown=!1}set(t){this.isDown!=t&&(this.isDown=t,this.view.update([]))}},{eventObservers:{keydown(t){this.set(t.keyCode==e||i(t))},keyup(t){t.keyCode!=e&&i(t)||this.set(!1)},mousemove(t){this.set(i(t))}}});return[n,Gs.contentAttributes.of((t=>{var e;return(null===(e=t.plugin(n))||void 0===e?void 0:e.isDown)?Lr:null}))]}const Ur="-10000px";class Hr{constructor(t,e,i,n){this.facet=e,this.createTooltipView=i,this.removeTooltipView=n,this.input=t.state.facet(e),this.tooltips=this.input.filter((t=>t)),this.tooltipViews=this.tooltips.map(i)}update(t,e){var i;let n=t.state.facet(this.facet),s=n.filter((t=>t));if(n===this.input){for(let e of this.tooltipViews)e.update&&e.update(t);return!1}let r=[],o=e?[]:null;for(let i=0;i<s.length;i++){let n=s[i],a=-1;if(n){for(let t=0;t<this.tooltips.length;t++){let e=this.tooltips[t];e&&e.create==n.create&&(a=t)}if(a<0)r[i]=this.createTooltipView(n),o&&(o[i]=!!n.above);else{let n=r[i]=this.tooltipViews[a];o&&(o[i]=e[a]),n.update&&n.update(t)}}}for(let t of this.tooltipViews)r.indexOf(t)<0&&(this.removeTooltipView(t),null===(i=t.destroy)||void 0===i||i.call(t));return e&&(o.forEach(((t,i)=>e[i]=t)),e.length=o.length),this.input=n,this.tooltips=s,this.tooltipViews=r,!0}}function Fr(t){let{win:e}=t;return{top:0,left:0,bottom:e.innerHeight,right:e.innerWidth}}const Jr=j.define({combine:t=>{var e,i,n;return{position:_e.ios?"absolute":(null===(e=t.find((t=>t.position)))||void 0===e?void 0:e.position)||"fixed",parent:(null===(i=t.find((t=>t.parent)))||void 0===i?void 0:i.parent)||null,tooltipSpace:(null===(n=t.find((t=>t.tooltipSpace)))||void 0===n?void 0:n.tooltipSpace)||Fr}}}),Kr=new WeakMap,to=Ni.fromClass(class{constructor(t){this.view=t,this.above=[],this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let e=t.state.facet(Jr);this.position=e.position,this.parent=e.parent,this.classes=t.themeClasses,this.createContainer(),this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this},this.resizeObserver="function"==typeof ResizeObserver?new ResizeObserver((()=>this.measureSoon())):null,this.manager=new Hr(t,no,(t=>this.createTooltip(t)),(t=>{this.resizeObserver&&this.resizeObserver.unobserve(t.dom),t.dom.remove()})),this.above=this.manager.tooltips.map((t=>!!t.above)),this.intersectionObserver="function"==typeof IntersectionObserver?new IntersectionObserver((t=>{Date.now()>this.lastTransaction-50&&t.length>0&&t[t.length-1].intersectionRatio<1&&this.measureSoon()}),{threshold:[1]}):null,this.observeIntersection(),t.win.addEventListener("resize",this.measureSoon=this.measureSoon.bind(this)),this.maybeMeasure()}createContainer(){this.parent?(this.container=document.createElement("div"),this.container.style.position="relative",this.container.className=this.view.themeClasses,this.parent.appendChild(this.container)):this.container=this.view.dom}observeIntersection(){if(this.intersectionObserver){this.intersectionObserver.disconnect();for(let t of this.manager.tooltipViews)this.intersectionObserver.observe(t.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout((()=>{this.measureTimeout=-1,this.maybeMeasure()}),50))}update(t){t.transactions.length&&(this.lastTransaction=Date.now());let e=this.manager.update(t,this.above);e&&this.observeIntersection();let i=e||t.geometryChanged,n=t.state.facet(Jr);if(n.position!=this.position&&!this.madeAbsolute){this.position=n.position;for(let t of this.manager.tooltipViews)t.dom.style.position=this.position;i=!0}if(n.parent!=this.parent){this.parent&&this.container.remove(),this.parent=n.parent,this.createContainer();for(let t of this.manager.tooltipViews)this.container.appendChild(t.dom);i=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);i&&this.maybeMeasure()}createTooltip(t){let e=t.create(this.view);if(e.dom.classList.add("cm-tooltip"),t.arrow&&!e.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let t=document.createElement("div");t.className="cm-tooltip-arrow",e.dom.appendChild(t)}return e.dom.style.position=this.position,e.dom.style.top=Ur,e.dom.style.left="0px",this.container.appendChild(e.dom),e.mount&&e.mount(this.view),this.resizeObserver&&this.resizeObserver.observe(e.dom),e}destroy(){var t,e,i;this.view.win.removeEventListener("resize",this.measureSoon);for(let e of this.manager.tooltipViews)e.dom.remove(),null===(t=e.destroy)||void 0===t||t.call(e);this.parent&&this.container.remove(),null===(e=this.resizeObserver)||void 0===e||e.disconnect(),null===(i=this.intersectionObserver)||void 0===i||i.disconnect(),clearTimeout(this.measureTimeout)}readMeasure(){let t=this.view.dom.getBoundingClientRect(),e=1,i=1,n=!1;if("fixed"==this.position&&this.manager.tooltipViews.length){let{dom:t}=this.manager.tooltipViews[0];if(_e.gecko)n=t.offsetParent!=this.container.ownerDocument.body;else if(t.style.top==Ur&&"0px"==t.style.left){let e=t.getBoundingClientRect();n=Math.abs(e.top+1e4)>1||Math.abs(e.left)>1}}if(n||"absolute"==this.position)if(this.parent){let t=this.parent.getBoundingClientRect();t.width&&t.height&&(e=t.width/this.parent.offsetWidth,i=t.height/this.parent.offsetHeight)}else({scaleX:e,scaleY:i}=this.view.viewState);return{editor:t,parent:this.parent?this.container.getBoundingClientRect():t,pos:this.manager.tooltips.map(((t,e)=>{let i=this.manager.tooltipViews[e];return i.getCoords?i.getCoords(t.pos):this.view.coordsAtPos(t.pos)})),size:this.manager.tooltipViews.map((({dom:t})=>t.getBoundingClientRect())),space:this.view.state.facet(Jr).tooltipSpace(this.view),scaleX:e,scaleY:i,makeAbsolute:n}}writeMeasure(t){var e;if(t.makeAbsolute){this.madeAbsolute=!0,this.position="absolute";for(let t of this.manager.tooltipViews)t.dom.style.position="absolute"}let{editor:i,space:n,scaleX:s,scaleY:r}=t,o=[];for(let a=0;a<this.manager.tooltips.length;a++){let l=this.manager.tooltips[a],h=this.manager.tooltipViews[a],{dom:c}=h,f=t.pos[a],u=t.size[a];if(!f||f.bottom<=Math.max(i.top,n.top)||f.top>=Math.min(i.bottom,n.bottom)||f.right<Math.max(i.left,n.left)-.1||f.left>Math.min(i.right,n.right)+.1){c.style.top=Ur;continue}let d=l.arrow?h.dom.querySelector(".cm-tooltip-arrow"):null,p=d?7:0,O=u.right-u.left,g=null!==(e=Kr.get(h))&&void 0!==e?e:u.bottom-u.top,m=h.offset||io,w=this.view.textDirection==di.LTR,v=u.width>n.right-n.left?w?n.left:n.right-u.width:w?Math.min(f.left-(d?14:0)+m.x,n.right-O):Math.max(n.left,f.left-O+(d?14:0)-m.x),b=this.above[a];!l.strictSide&&(b?f.top-(u.bottom-u.top)-m.y<n.top:f.bottom+(u.bottom-u.top)+m.y>n.bottom)&&b==n.bottom-f.bottom>f.top-n.top&&(b=this.above[a]=!b);let y=(b?f.top-n.top:n.bottom-f.bottom)-p;if(y<g&&!1!==h.resize){if(y<this.view.defaultLineHeight){c.style.top=Ur;continue}Kr.set(h,g),c.style.height=(g=y)/r+"px"}else c.style.height&&(c.style.height="");let S=b?f.top-g-p-m.y:f.bottom+p+m.y,x=v+O;if(!0!==h.overlap)for(let t of o)t.left<x&&t.right>v&&t.top<S+g&&t.bottom>S&&(S=b?t.top-g-2-p:t.bottom+p+2);if("absolute"==this.position?(c.style.top=(S-t.parent.top)/r+"px",c.style.left=(v-t.parent.left)/s+"px"):(c.style.top=S/r+"px",c.style.left=v/s+"px"),d){let t=f.left+(w?m.x:-m.x)-(v+14-7);d.style.left=t/s+"px"}!0!==h.overlap&&o.push({left:v,top:S,right:x,bottom:S+g}),c.classList.toggle("cm-tooltip-above",b),c.classList.toggle("cm-tooltip-below",!b),h.positioned&&h.positioned(t.space)}}maybeMeasure(){if(this.manager.tooltips.length&&(this.view.inView&&this.view.requestMeasure(this.measureReq),this.inView!=this.view.inView&&(this.inView=this.view.inView,!this.inView)))for(let t of this.manager.tooltipViews)t.dom.style.top=Ur}},{eventObservers:{scroll(){this.maybeMeasure()}}}),eo=Gs.baseTheme({".cm-tooltip":{zIndex:100,boxSizing:"border-box"},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:"7px",width:"14px",position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:"7px solid transparent",borderRight:"7px solid transparent"},".cm-tooltip-above &":{bottom:"-7px","&:before":{borderTop:"7px solid #bbb"},"&:after":{borderTop:"7px solid #f5f5f5",bottom:"1px"}},".cm-tooltip-below &":{top:"-7px","&:before":{borderBottom:"7px solid #bbb"},"&:after":{borderBottom:"7px solid #f5f5f5",top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}}),io={x:0,y:0},no=j.define({enables:[to,eo]}),so=j.define();class ro{static create(t){return new ro(t)}constructor(t){this.view=t,this.mounted=!1,this.dom=document.createElement("div"),this.dom.classList.add("cm-tooltip-hover"),this.manager=new Hr(t,so,(t=>this.createHostedView(t)),(t=>t.dom.remove()))}createHostedView(t){let e=t.create(this.view);return e.dom.classList.add("cm-tooltip-section"),this.dom.appendChild(e.dom),this.mounted&&e.mount&&e.mount(this.view),e}mount(t){for(let e of this.manager.tooltipViews)e.mount&&e.mount(t);this.mounted=!0}positioned(t){for(let e of this.manager.tooltipViews)e.positioned&&e.positioned(t)}update(t){this.manager.update(t)}destroy(){var t;for(let e of this.manager.tooltipViews)null===(t=e.destroy)||void 0===t||t.call(e)}passProp(t){let e;for(let i of this.manager.tooltipViews){let n=i[t];if(void 0!==n)if(void 0===e)e=n;else if(e!==n)return}return e}get offset(){return this.passProp("offset")}get getCoords(){return this.passProp("getCoords")}get overlap(){return this.passProp("overlap")}get resize(){return this.passProp("resize")}}const oo=no.compute([so],(t=>{let e=t.facet(so).filter((t=>t));return 0===e.length?null:{pos:Math.min(...e.map((t=>t.pos))),end:Math.max(...e.map((t=>{var e;return null!==(e=t.end)&&void 0!==e?e:t.pos}))),create:ro.create,above:e[0].above,arrow:e.some((t=>t.arrow))}}));class ao{constructor(t,e,i,n,s){this.view=t,this.source=e,this.field=i,this.setHover=n,this.hoverTime=s,this.hoverTimeout=-1,this.restartTimeout=-1,this.pending=null,this.lastMove={x:0,y:0,target:t.dom,time:0},this.checkHover=this.checkHover.bind(this),t.dom.addEventListener("mouseleave",this.mouseleave=this.mouseleave.bind(this)),t.dom.addEventListener("mousemove",this.mousemove=this.mousemove.bind(this))}update(){this.pending&&(this.pending=null,clearTimeout(this.restartTimeout),this.restartTimeout=setTimeout((()=>this.startHover()),20))}get active(){return this.view.state.field(this.field)}checkHover(){if(this.hoverTimeout=-1,this.active)return;let t=Date.now()-this.lastMove.time;t<this.hoverTime?this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime-t):this.startHover()}startHover(){clearTimeout(this.restartTimeout);let{view:t,lastMove:e}=this,i=t.docView.nearest(e.target);if(!i)return;let n,s=1;if(i instanceof ze)n=i.posAtStart;else{if(n=t.posAtCoords(e),null==n)return;let i=t.coordsAtPos(n);if(!i||e.y<i.top||e.y>i.bottom||e.x<i.left-t.defaultCharacterWidth||e.x>i.right+t.defaultCharacterWidth)return;let r=t.bidiSpans(t.state.doc.lineAt(n)).find((t=>t.from<=n&&t.to>=n)),o=r&&r.dir==di.RTL?-1:1;s=e.x<i.left?-o:o}let r=this.source(t,n,s);if(null==r?void 0:r.then){let e=this.pending={pos:n};r.then((i=>{this.pending==e&&(this.pending=null,i&&t.dispatch({effects:this.setHover.of(i)}))}),(e=>zi(t.state,e,"hover tooltip")))}else r&&t.dispatch({effects:this.setHover.of(r)})}get tooltip(){let t=this.view.plugin(to),e=t?t.manager.tooltips.findIndex((t=>t.create==ro.create)):-1;return e>-1?t.manager.tooltipViews[e]:null}mousemove(t){var e;this.lastMove={x:t.clientX,y:t.clientY,target:t.target,time:Date.now()},this.hoverTimeout<0&&(this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime));let{active:i,tooltip:n}=this;if(i&&n&&!function(t,e){let i=t.getBoundingClientRect();return e.clientX>=i.left-lo&&e.clientX<=i.right+lo&&e.clientY>=i.top-lo&&e.clientY<=i.bottom+lo}(n.dom,t)||this.pending){let{pos:n}=i||this.pending,s=null!==(e=null==i?void 0:i.end)&&void 0!==e?e:n;(n==s?this.view.posAtCoords(this.lastMove)==n:function(t,e,i,n,s,r){let o=t.scrollDOM.getBoundingClientRect(),a=t.documentTop+t.documentPadding.top+t.contentHeight;if(o.left>n||o.right<n||o.top>s||Math.min(o.bottom,a)<s)return!1;let l=t.posAtCoords({x:n,y:s},!1);return l>=e&&l<=i}(this.view,n,s,t.clientX,t.clientY))||(this.view.dispatch({effects:this.setHover.of(null)}),this.pending=null)}}mouseleave(t){clearTimeout(this.hoverTimeout),this.hoverTimeout=-1;let{active:e}=this;if(e){let{tooltip:e}=this;e&&e.dom.contains(t.relatedTarget)?this.watchTooltipLeave(e.dom):this.view.dispatch({effects:this.setHover.of(null)})}}watchTooltipLeave(t){let e=i=>{t.removeEventListener("mouseleave",e),this.active&&!this.view.dom.contains(i.relatedTarget)&&this.view.dispatch({effects:this.setHover.of(null)})};t.addEventListener("mouseleave",e)}destroy(){clearTimeout(this.hoverTimeout),this.view.dom.removeEventListener("mouseleave",this.mouseleave),this.view.dom.removeEventListener("mousemove",this.mousemove)}}const lo=4;function ho(t,e={}){let i=dt.define(),n=z.define({create:()=>null,update(t,n){if(t&&(e.hideOnChange&&(n.docChanged||n.selection)||e.hideOn&&e.hideOn(n,t)))return null;if(t&&n.docChanged){let e=n.changes.mapPos(t.pos,-1,k.TrackDel);if(null==e)return null;let i=Object.assign(Object.create(null),t);i.pos=e,null!=t.end&&(i.end=n.changes.mapPos(t.end)),t=i}for(let e of n.effects)e.is(i)&&(t=e.value),e.is(fo)&&(t=null);return t},provide:t=>so.from(t)});return[n,Ni.define((s=>new ao(s,t,n,i,e.hoverTime||300))),oo]}function co(t,e){let i=t.plugin(to);if(!i)return null;let n=i.manager.tooltips.indexOf(e);return n<0?null:i.manager.tooltipViews[n]}const fo=dt.define(),uo=fo.of(null);const po=j.define({combine(t){let e,i;for(let n of t)e=e||n.topContainer,i=i||n.bottomContainer;return{topContainer:e,bottomContainer:i}}});function Oo(t,e){let i=t.plugin(go),n=i?i.specs.indexOf(e):-1;return n>-1?i.panels[n]:null}const go=Ni.fromClass(class{constructor(t){this.input=t.state.facet(vo),this.specs=this.input.filter((t=>t)),this.panels=this.specs.map((e=>e(t)));let e=t.state.facet(po);this.top=new mo(t,!0,e.topContainer),this.bottom=new mo(t,!1,e.bottomContainer),this.top.sync(this.panels.filter((t=>t.top))),this.bottom.sync(this.panels.filter((t=>!t.top)));for(let t of this.panels)t.dom.classList.add("cm-panel"),t.mount&&t.mount()}update(t){let e=t.state.facet(po);this.top.container!=e.topContainer&&(this.top.sync([]),this.top=new mo(t.view,!0,e.topContainer)),this.bottom.container!=e.bottomContainer&&(this.bottom.sync([]),this.bottom=new mo(t.view,!1,e.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let i=t.state.facet(vo);if(i!=this.input){let e=i.filter((t=>t)),n=[],s=[],r=[],o=[];for(let i of e){let e,a=this.specs.indexOf(i);a<0?(e=i(t.view),o.push(e)):(e=this.panels[a],e.update&&e.update(t)),n.push(e),(e.top?s:r).push(e)}this.specs=e,this.panels=n,this.top.sync(s),this.bottom.sync(r);for(let t of o)t.dom.classList.add("cm-panel"),t.mount&&t.mount()}else for(let e of this.panels)e.update&&e.update(t)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:t=>Gs.scrollMargins.of((e=>{let i=e.plugin(t);return i&&{top:i.top.scrollMargin(),bottom:i.bottom.scrollMargin()}}))});class mo{constructor(t,e,i){this.view=t,this.top=e,this.container=i,this.dom=void 0,this.classes="",this.panels=[],this.syncClasses()}sync(t){for(let e of this.panels)e.destroy&&t.indexOf(e)<0&&e.destroy();this.panels=t,this.syncDOM()}syncDOM(){if(0==this.panels.length)return void(this.dom&&(this.dom.remove(),this.dom=void 0));if(!this.dom){this.dom=document.createElement("div"),this.dom.className=this.top?"cm-panels cm-panels-top":"cm-panels cm-panels-bottom",this.dom.style[this.top?"top":"bottom"]="0";let t=this.container||this.view.dom;t.insertBefore(this.dom,this.top?t.firstChild:null)}let t=this.dom.firstChild;for(let e of this.panels)if(e.dom.parentNode==this.dom){for(;t!=e.dom;)t=wo(t);t=t.nextSibling}else this.dom.insertBefore(e.dom,t);for(;t;)t=wo(t)}scrollMargin(){return!this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top)}syncClasses(){if(this.container&&this.classes!=this.view.themeClasses){for(let t of this.classes.split(" "))t&&this.container.classList.remove(t);for(let t of(this.classes=this.view.themeClasses).split(" "))t&&this.container.classList.add(t)}}}function wo(t){let e=t.nextSibling;return t.remove(),e}const vo=j.define({enables:go});class bo extends Pt{compare(t){return this==t||this.constructor==t.constructor&&this.eq(t)}eq(t){return!1}destroy(t){}}bo.prototype.elementClass="",bo.prototype.toDOM=void 0,bo.prototype.mapMode=k.TrackBefore,bo.prototype.startSide=bo.prototype.endSide=-1,bo.prototype.point=!0;const yo=j.define(),So={class:"",renderEmptyElements:!1,elementStyle:"",markers:()=>At.empty,lineMarker:()=>null,widgetMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{}},xo=j.define();function ko(t){return[$o(),xo.of(Object.assign(Object.assign({},So),t))]}const Qo=j.define({combine:t=>t.some((t=>t))});function $o(t){let e=[Po];return t&&!1===t.fixed&&e.push(Qo.of(!0)),e}const Po=Ni.fromClass(class{constructor(t){this.view=t,this.prevViewport=t.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=t.state.facet(xo).map((e=>new Ao(t,e)));for(let t of this.gutters)this.dom.appendChild(t.dom);this.fixed=!t.state.facet(Qo),this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),t.scrollDOM.insertBefore(this.dom,t.contentDOM)}update(t){if(this.updateGutters(t)){let e=this.prevViewport,i=t.view.viewport,n=Math.min(e.to,i.to)-Math.max(e.from,i.from);this.syncGutters(n<.8*(i.to-i.from))}t.geometryChanged&&(this.dom.style.minHeight=this.view.contentHeight+"px"),this.view.state.facet(Qo)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":""),this.prevViewport=t.view.viewport}syncGutters(t){let e=this.dom.nextSibling;t&&this.dom.remove();let i=At.iter(this.view.state.facet(yo),this.view.viewport.from),n=[],s=this.gutters.map((t=>new To(t,this.view.viewport,-this.view.documentPadding.top)));for(let t of this.view.viewportLineBlocks)if(n.length&&(n=[]),Array.isArray(t.type)){let e=!0;for(let r of t.type)if(r.type==ni.Text&&e){Co(i,n,r.from);for(let t of s)t.line(this.view,r,n);e=!1}else if(r.widget)for(let t of s)t.widget(this.view,r)}else if(t.type==ni.Text){Co(i,n,t.from);for(let e of s)e.line(this.view,t,n)}else if(t.widget)for(let e of s)e.widget(this.view,t);for(let t of s)t.finish();t&&this.view.scrollDOM.insertBefore(this.dom,e)}updateGutters(t){let e=t.startState.facet(xo),i=t.state.facet(xo),n=t.docChanged||t.heightChanged||t.viewportChanged||!At.eq(t.startState.facet(yo),t.state.facet(yo),t.view.viewport.from,t.view.viewport.to);if(e==i)for(let e of this.gutters)e.update(t)&&(n=!0);else{n=!0;let s=[];for(let n of i){let i=e.indexOf(n);i<0?s.push(new Ao(this.view,n)):(this.gutters[i].update(t),s.push(this.gutters[i]))}for(let t of this.gutters)t.dom.remove(),s.indexOf(t)<0&&t.destroy();for(let t of s)this.dom.appendChild(t.dom);this.gutters=s}return n}destroy(){for(let t of this.gutters)t.destroy();this.dom.remove()}},{provide:t=>Gs.scrollMargins.of((e=>{let i=e.plugin(t);return i&&0!=i.gutters.length&&i.fixed?e.textDirection==di.LTR?{left:i.dom.offsetWidth*e.scaleX}:{right:i.dom.offsetWidth*e.scaleX}:null}))});function Zo(t){return Array.isArray(t)?t:[t]}function Co(t,e,i){for(;t.value&&t.from<=i;)t.from==i&&e.push(t.value),t.next()}class To{constructor(t,e,i){this.gutter=t,this.height=i,this.i=0,this.cursor=At.iter(t.markers,e.from)}addElement(t,e,i){let{gutter:n}=this,s=(e.top-this.height)/t.scaleY,r=e.height/t.scaleY;if(this.i==n.elements.length){let e=new Ro(t,r,s,i);n.elements.push(e),n.dom.appendChild(e.dom)}else n.elements[this.i].update(t,r,s,i);this.height=e.bottom,this.i++}line(t,e,i){let n=[];Co(this.cursor,n,e.from),i.length&&(n=n.concat(i));let s=this.gutter.config.lineMarker(t,e,n);s&&n.unshift(s);let r=this.gutter;(0!=n.length||r.config.renderEmptyElements)&&this.addElement(t,e,n)}widget(t,e){let i=this.gutter.config.widgetMarker(t,e.widget,e);i&&this.addElement(t,e,[i])}finish(){let t=this.gutter;for(;t.elements.length>this.i;){let e=t.elements.pop();t.dom.removeChild(e.dom),e.destroy()}}}class Ao{constructor(t,e){this.view=t,this.config=e,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let i in e.domEventHandlers)this.dom.addEventListener(i,(n=>{let s,r=n.target;if(r!=this.dom&&this.dom.contains(r)){for(;r.parentNode!=this.dom;)r=r.parentNode;let t=r.getBoundingClientRect();s=(t.top+t.bottom)/2}else s=n.clientY;let o=t.lineBlockAtHeight(s-t.documentTop);e.domEventHandlers[i](t,o,n)&&n.preventDefault()}));this.markers=Zo(e.markers(t)),e.initialSpacer&&(this.spacer=new Ro(t,0,0,[e.initialSpacer(t)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(t){let e=this.markers;if(this.markers=Zo(this.config.markers(t.view)),this.spacer&&this.config.updateSpacer){let e=this.config.updateSpacer(this.spacer.markers[0],t);e!=this.spacer.markers[0]&&this.spacer.update(t.view,0,0,[e])}let i=t.view.viewport;return!At.eq(this.markers,e,i.from,i.to)||!!this.config.lineMarkerChange&&this.config.lineMarkerChange(t)}destroy(){for(let t of this.elements)t.destroy()}}class Ro{constructor(t,e,i,n){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(t,e,i,n)}update(t,e,i,n){this.height!=e&&(this.height=e,this.dom.style.height=e+"px"),this.above!=i&&(this.dom.style.marginTop=(this.above=i)?i+"px":""),function(t,e){if(t.length!=e.length)return!1;for(let i=0;i<t.length;i++)if(!t[i].compare(e[i]))return!1;return!0}(this.markers,n)||this.setMarkers(t,n)}setMarkers(t,e){let i="cm-gutterElement",n=this.dom.firstChild;for(let s=0,r=0;;){let o=r,a=s<e.length?e[s++]:null,l=!1;if(a){let t=a.elementClass;t&&(i+=" "+t);for(let t=r;t<this.markers.length;t++)if(this.markers[t].compare(a)){o=t,l=!0;break}}else o=this.markers.length;for(;r<o;){let t=this.markers[r++];if(t.toDOM){t.destroy(n);let e=n.nextSibling;n.remove(),n=e}}if(!a)break;a.toDOM&&(l?n=n.nextSibling:this.dom.insertBefore(a.toDOM(t),n)),l&&r++}this.dom.className=i,this.markers=e}destroy(){this.setMarkers(null,[])}}const Xo=j.define(),Yo=j.define({combine:t=>$t(t,{formatNumber:String,domEventHandlers:{}},{domEventHandlers(t,e){let i=Object.assign({},t);for(let t in e){let n=i[t],s=e[t];i[t]=n?(t,e,i)=>n(t,e,i)||s(t,e,i):s}return i}})});class Wo extends bo{constructor(t){super(),this.number=t}eq(t){return this.number==t.number}toDOM(){return document.createTextNode(this.number)}}function Mo(t,e){return t.state.facet(Yo).formatNumber(e,t.state)}const jo=xo.compute([Yo],(t=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers:t=>t.state.facet(Xo),lineMarker:(t,e,i)=>i.some((t=>t.toDOM))?null:new Wo(Mo(t,t.state.doc.lineAt(e.from).number)),widgetMarker:()=>null,lineMarkerChange:t=>t.startState.facet(Yo)!=t.state.facet(Yo),initialSpacer:t=>new Wo(Mo(t,Eo(t.state.doc.lines))),updateSpacer(t,e){let i=Mo(e.view,Eo(e.view.state.doc.lines));return i==t.number?t:new Wo(i)},domEventHandlers:t.facet(Yo).domEventHandlers})));function Do(t={}){return[Yo.of(t),$o(),jo]}function Eo(t){let e=9;for(;e<t;)e=10*e+9;return e}const qo=new class extends bo{constructor(){super(...arguments),this.elementClass="cm-activeLineGutter"}},_o=yo.compute(["selection"],(t=>{let e=[],i=-1;for(let n of t.selection.ranges){let s=t.doc.lineAt(n.head).from;s>i&&(i=s,e.push(qo.range(s)))}return At.of(e)}));function Vo(){return _o}const Io=new Map;function zo(t){return Ni.define((e=>({decorations:t.createDeco(e),update(e){this.decorations=t.updateDeco(e,this.decorations)}})),{decorations:t=>t.decorations})}const Bo=zo(new Pr({regexp:/\t| +/g,decoration:t=>function(t){let e=Io.get(t);return e||Io.set(t,e=si.mark({attributes:"\t"===t?{class:"cm-highlightTab"}:{class:"cm-highlightSpace","data-display":t.replace(/ /g,"·")}})),e}(t[0]),boundary:/\S/}));const Go=zo(new Pr({regexp:/\s+$/g,decoration:si.mark({class:"cm-trailingSpace"}),boundary:/\S/}));const Lo={HeightMap:as,HeightOracle:is,MeasuredHeights:ns,QueryType:rs,ChangedRange:an,computeOrder:Zi,moveVisually:Ai};var No=Object.freeze({__proto__:null,BidiSpan:xi,BlockInfo:ss,get BlockType(){return ni},Decoration:si,get Direction(){return di},EditorView:Gs,GutterMarker:bo,MatchDecorator:Pr,RectangleMarker:ar,ViewPlugin:Ni,ViewUpdate:ln,WidgetType:ii,__test:Lo,closeHoverTooltips:uo,crosshairCursor:Nr,drawSelection:Or,dropCursor:Qr,getDrawSelectionConfig:function(t){return t.facet(pr)},getPanel:Oo,getTooltip:co,gutter:ko,gutterLineClass:yo,gutters:$o,hasHoverTooltips:function(t){return t.facet(so).some((t=>t))},highlightActiveLine:Dr,highlightActiveLineGutter:Vo,highlightSpecialChars:Xr,highlightTrailingWhitespace:function(){return Go},highlightWhitespace:function(){return Bo},hoverTooltip:ho,keymap:tr,layer:ur,lineNumberMarkers:Xo,lineNumbers:Do,logException:zi,panels:function(t){return t?[po.of(t)]:[]},placeholder:function(t){return Ni.fromClass(class{constructor(e){this.view=e,this.placeholder=t?si.set([si.widget({widget:new _r(t),side:1}).range(0)]):si.none}get decorations(){return this.view.state.doc.length?si.none:this.placeholder}},{decorations:t=>t.decorations})},rectangularSelection:Br,repositionTooltips:function(t){let e=t.plugin(to);e&&e.maybeMeasure()},runScopeHandlers:nr,scrollPastEnd:function(){return[jr,Fi.of((t=>{var e;return(null===(e=t.plugin(jr))||void 0===e?void 0:e.attrs)||null}))]},showPanel:vo,showTooltip:no,tooltips:function(t={}){return Jr.of(t)}});const Uo=1024;let Ho=0;class Fo{constructor(t,e){this.from=t,this.to=e}}class Jo{constructor(t={}){this.id=Ho++,this.perNode=!!t.perNode,this.deserialize=t.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")})}add(t){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return"function"!=typeof t&&(t=ea.match(t)),e=>{let i=t(e);return void 0===i?null:[this,i]}}}Jo.closedBy=new Jo({deserialize:t=>t.split(" ")}),Jo.openedBy=new Jo({deserialize:t=>t.split(" ")}),Jo.group=new Jo({deserialize:t=>t.split(" ")}),Jo.isolate=new Jo({deserialize:t=>{if(t&&"rtl"!=t&&"ltr"!=t&&"auto"!=t)throw new RangeError("Invalid value for isolate: "+t);return t||"auto"}}),Jo.contextHash=new Jo({perNode:!0}),Jo.lookAhead=new Jo({perNode:!0}),Jo.mounted=new Jo({perNode:!0});class Ko{constructor(t,e,i){this.tree=t,this.overlay=e,this.parser=i}static get(t){return t&&t.props&&t.props[Jo.mounted.id]}}const ta=Object.create(null);class ea{constructor(t,e,i,n=0){this.name=t,this.props=e,this.id=i,this.flags=n}static define(t){let e=t.props&&t.props.length?Object.create(null):ta,i=(t.top?1:0)|(t.skipped?2:0)|(t.error?4:0)|(null==t.name?8:0),n=new ea(t.name||"",e,t.id,i);if(t.props)for(let i of t.props)if(Array.isArray(i)||(i=i(n)),i){if(i[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");e[i[0].id]=i[1]}return n}prop(t){return this.props[t.id]}get isTop(){return(1&this.flags)>0}get isSkipped(){return(2&this.flags)>0}get isError(){return(4&this.flags)>0}get isAnonymous(){return(8&this.flags)>0}is(t){if("string"==typeof t){if(this.name==t)return!0;let e=this.prop(Jo.group);return!!e&&e.indexOf(t)>-1}return this.id==t}static match(t){let e=Object.create(null);for(let i in t)for(let n of i.split(" "))e[n]=t[i];return t=>{for(let i=t.prop(Jo.group),n=-1;n<(i?i.length:0);n++){let s=e[n<0?t.name:i[n]];if(s)return s}}}}ea.none=new ea("",Object.create(null),0,8);class ia{constructor(t){this.types=t;for(let e=0;e<t.length;e++)if(t[e].id!=e)throw new RangeError("Node type ids should correspond to array positions when creating a node set")}extend(...t){let e=[];for(let i of this.types){let n=null;for(let e of t){let t=e(i);t&&(n||(n=Object.assign({},i.props)),n[t[0].id]=t[1])}e.push(n?new ea(i.name,n,i.id,i.flags):i)}return new ia(e)}}const na=new WeakMap,sa=new WeakMap;var ra;!function(t){t[t.ExcludeBuffers=1]="ExcludeBuffers",t[t.IncludeAnonymous=2]="IncludeAnonymous",t[t.IgnoreMounts=4]="IgnoreMounts",t[t.IgnoreOverlays=8]="IgnoreOverlays"}(ra||(ra={}));class oa{constructor(t,e,i,n,s){if(this.type=t,this.children=e,this.positions=i,this.length=n,this.props=null,s&&s.length){this.props=Object.create(null);for(let[t,e]of s)this.props["number"==typeof t?t:t.id]=e}}toString(){let t=Ko.get(this);if(t&&!t.overlay)return t.tree.toString();let e="";for(let t of this.children){let i=t.toString();i&&(e&&(e+=","),e+=i)}return this.type.name?(/\W/.test(this.type.name)&&!this.type.isError?JSON.stringify(this.type.name):this.type.name)+(e.length?"("+e+")":""):e}cursor(t=0){return new va(this.topNode,t)}cursorAt(t,e=0,i=0){let n=na.get(this)||this.topNode,s=new va(n);return s.moveTo(t,e),na.set(this,s._tree),s}get topNode(){return new ua(this,0,0,null)}resolve(t,e=0){let i=ca(na.get(this)||this.topNode,t,e,!1);return na.set(this,i),i}resolveInner(t,e=0){let i=ca(sa.get(this)||this.topNode,t,e,!0);return sa.set(this,i),i}resolveStack(t,e=0){return function(t,e,i){let n=t.resolveInner(e,i),s=null;for(let t=n instanceof ua?n:n.context.parent;t;t=t.parent)if(t.index<0){let r=t.parent;(s||(s=[n])).push(r.resolve(e,i)),t=r}else{let r=Ko.get(t.tree);if(r&&r.overlay&&r.overlay[0].from<=e&&r.overlay[r.overlay.length-1].to>=e){let o=new ua(r.tree,r.overlay[0].from+t.from,-1,t);(s||(s=[n])).push(ca(o,e,i,!1))}}return s?ma(s):n}(this,t,e)}iterate(t){let{enter:e,leave:i,from:n=0,to:s=this.length}=t,r=t.mode||0,o=(r&ra.IncludeAnonymous)>0;for(let t=this.cursor(r|ra.IncludeAnonymous);;){let r=!1;if(t.from<=s&&t.to>=n&&(!o&&t.type.isAnonymous||!1!==e(t))){if(t.firstChild())continue;r=!0}for(;r&&i&&(o||!t.type.isAnonymous)&&i(t),!t.nextSibling();){if(!t.parent())return;r=!0}}}prop(t){return t.perNode?this.props?this.props[t.id]:void 0:this.type.prop(t)}get propValues(){let t=[];if(this.props)for(let e in this.props)t.push([+e,this.props[e]]);return t}balance(t={}){return this.children.length<=8?this:xa(ea.none,this.children,this.positions,0,this.children.length,0,this.length,((t,e,i)=>new oa(this.type,t,e,i,this.propValues)),t.makeTree||((t,e,i)=>new oa(ea.none,t,e,i)))}static build(t){return function(t){var e;let{buffer:i,nodeSet:n,maxBufferLength:s=Uo,reused:r=[],minRepeatType:o=n.types.length}=t,a=Array.isArray(i)?new aa(i,i.length):i,l=n.types,h=0,c=0;function f(t,e,i,w,v,b){let{id:y,start:S,end:x,size:k}=a,Q=c;for(;k<0;){if(a.next(),-1==k){let e=r[y];return i.push(e),void w.push(S-t)}if(-3==k)return void(h=y);if(-4==k)return void(c=y);throw new RangeError(`Unrecognized record size: ${k}`)}let $,P,Z=l[y],C=S-t;if(x-S<=s&&(P=g(a.pos-e,v))){let e=new Uint16Array(P.size-P.skip),i=a.pos-P.size,s=e.length;for(;a.pos>i;)s=m(P.start,e,s);$=new la(e,x-P.start,n),C=P.start-t}else{let t=a.pos-k;a.next();let e=[],i=[],n=y>=o?y:-1,r=0,l=x;for(;a.pos>t;)n>=0&&a.id==n&&a.size>=0?(a.end<=l-s&&(p(e,i,S,r,a.end,l,n,Q),r=e.length,l=a.end),a.next()):b>2500?u(S,t,e,i):f(S,t,e,i,n,b+1);if(n>=0&&r>0&&r<e.length&&p(e,i,S,r,S,l,n,Q),e.reverse(),i.reverse(),n>-1&&r>0){let t=d(Z);$=xa(Z,e,i,0,e.length,0,x-S,t,t)}else $=O(Z,e,i,x-S,Q-x)}i.push($),w.push(C)}function u(t,e,i,r){let o=[],l=0,h=-1;for(;a.pos>e;){let{id:t,start:e,end:i,size:n}=a;if(n>4)a.next();else{if(h>-1&&e<h)break;h<0&&(h=i-s),o.push(t,e,i),l++,a.next()}}if(l){let e=new Uint16Array(4*l),s=o[o.length-2];for(let t=o.length-3,i=0;t>=0;t-=3)e[i++]=o[t],e[i++]=o[t+1]-s,e[i++]=o[t+2]-s,e[i++]=i;i.push(new la(e,o[2]-s,n)),r.push(s-t)}}function d(t){return(e,i,n)=>{let s,r,o=0,a=e.length-1;if(a>=0&&(s=e[a])instanceof oa){if(!a&&s.type==t&&s.length==n)return s;(r=s.prop(Jo.lookAhead))&&(o=i[a]+s.length+r)}return O(t,e,i,n,o)}}function p(t,e,i,s,r,o,a,l){let h=[],c=[];for(;t.length>s;)h.push(t.pop()),c.push(e.pop()+i-r);t.push(O(n.types[a],h,c,o-r,l-o)),e.push(r-i)}function O(t,e,i,n,s=0,r){if(h){let t=[Jo.contextHash,h];r=r?[t].concat(r):[t]}if(s>25){let t=[Jo.lookAhead,s];r=r?[t].concat(r):[t]}return new oa(t,e,i,n,r)}function g(t,e){let i=a.fork(),n=0,r=0,l=0,h=i.end-s,c={size:0,start:0,skip:0};t:for(let s=i.pos-t;i.pos>s;){let t=i.size;if(i.id==e&&t>=0){c.size=n,c.start=r,c.skip=l,l+=4,n+=4,i.next();continue}let a=i.pos-t;if(t<0||a<s||i.start<h)break;let f=i.id>=o?4:0,u=i.start;for(i.next();i.pos>a;){if(i.size<0){if(-3!=i.size)break t;f+=4}else i.id>=o&&(f+=4);i.next()}r=u,n+=t,l+=f}return(e<0||n==t)&&(c.size=n,c.start=r,c.skip=l),c.size>4?c:void 0}function m(t,e,i){let{id:n,start:s,end:r,size:l}=a;if(a.next(),l>=0&&n<o){let o=i;if(l>4){let n=a.pos-(l-4);for(;a.pos>n;)i=m(t,e,i)}e[--i]=o,e[--i]=r-t,e[--i]=s-t,e[--i]=n}else-3==l?h=n:-4==l&&(c=n);return i}let w=[],v=[];for(;a.pos>0;)f(t.start||0,t.bufferStart||0,w,v,-1,0);let b=null!==(e=t.length)&&void 0!==e?e:w.length?v[0]+w[0].length:0;return new oa(l[t.topID],w.reverse(),v.reverse(),b)}(t)}}oa.empty=new oa(ea.none,[],[],0);class aa{constructor(t,e){this.buffer=t,this.index=e}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new aa(this.buffer,this.index)}}class la{constructor(t,e,i){this.buffer=t,this.length=e,this.set=i}get type(){return ea.none}toString(){let t=[];for(let e=0;e<this.buffer.length;)t.push(this.childString(e)),e=this.buffer[e+3];return t.join(",")}childString(t){let e=this.buffer[t],i=this.buffer[t+3],n=this.set.types[e],s=n.name;if(/\W/.test(s)&&!n.isError&&(s=JSON.stringify(s)),i==(t+=4))return s;let r=[];for(;t<i;)r.push(this.childString(t)),t=this.buffer[t+3];return s+"("+r.join(",")+")"}findChild(t,e,i,n,s){let{buffer:r}=this,o=-1;for(let a=t;a!=e&&!(ha(s,n,r[a+1],r[a+2])&&(o=a,i>0));a=r[a+3]);return o}slice(t,e,i){let n=this.buffer,s=new Uint16Array(e-t),r=0;for(let o=t,a=0;o<e;){s[a++]=n[o++],s[a++]=n[o++]-i;let e=s[a++]=n[o++]-i;s[a++]=n[o++]-t,r=Math.max(r,e)}return new la(s,r,this.set)}}function ha(t,e,i,n){switch(t){case-2:return i<e;case-1:return n>=e&&i<e;case 0:return i<e&&n>e;case 1:return i<=e&&n>e;case 2:return n>e;case 4:return!0}}function ca(t,e,i,n){for(var s;t.from==t.to||(i<1?t.from>=e:t.from>e)||(i>-1?t.to<=e:t.to<e);){let e=!n&&t instanceof ua&&t.index<0?null:t.parent;if(!e)return t;t=e}let r=n?0:ra.IgnoreOverlays;if(n)for(let n=t,o=n.parent;o;n=o,o=n.parent)n instanceof ua&&n.index<0&&(null===(s=o.enter(e,i,r))||void 0===s?void 0:s.from)!=n.from&&(t=o);for(;;){let n=t.enter(e,i,r);if(!n)return t;t=n}}class fa{cursor(t=0){return new va(this,t)}getChild(t,e=null,i=null){let n=da(this,t,e,i);return n.length?n[0]:null}getChildren(t,e=null,i=null){return da(this,t,e,i)}resolve(t,e=0){return ca(this,t,e,!1)}resolveInner(t,e=0){return ca(this,t,e,!0)}matchContext(t){return pa(this,t)}enterUnfinishedNodesBefore(t){let e=this.childBefore(t),i=this;for(;e;){let t=e.lastChild;if(!t||t.to!=e.to)break;t.type.isError&&t.from==t.to?(i=e,e=t.prevSibling):e=t}return i}get node(){return this}get next(){return this.parent}}class ua extends fa{constructor(t,e,i,n){super(),this._tree=t,this.from=e,this.index=i,this._parent=n}get type(){return this._tree.type}get name(){return this._tree.type.name}get to(){return this.from+this._tree.length}nextChild(t,e,i,n,s=0){for(let r=this;;){for(let{children:o,positions:a}=r._tree,l=e>0?o.length:-1;t!=l;t+=e){let l=o[t],h=a[t]+r.from;if(ha(n,i,h,h+l.length))if(l instanceof la){if(s&ra.ExcludeBuffers)continue;let o=l.findChild(0,l.buffer.length,e,i-h,n);if(o>-1)return new ga(new Oa(r,l,t,h),null,o)}else if(s&ra.IncludeAnonymous||!l.type.isAnonymous||ba(l)){let o;if(!(s&ra.IgnoreMounts)&&(o=Ko.get(l))&&!o.overlay)return new ua(o.tree,h,t,r);let a=new ua(l,h,t,r);return s&ra.IncludeAnonymous||!a.type.isAnonymous?a:a.nextChild(e<0?l.children.length-1:0,e,i,n)}}if(s&ra.IncludeAnonymous||!r.type.isAnonymous)return null;if(t=r.index>=0?r.index+e:e<0?-1:r._parent._tree.children.length,r=r._parent,!r)return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(t){return this.nextChild(0,1,t,2)}childBefore(t){return this.nextChild(this._tree.children.length-1,-1,t,-2)}enter(t,e,i=0){let n;if(!(i&ra.IgnoreOverlays)&&(n=Ko.get(this._tree))&&n.overlay){let i=t-this.from;for(let{from:t,to:s}of n.overlay)if((e>0?t<=i:t<i)&&(e<0?s>=i:s>i))return new ua(n.tree,n.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,t,e,i)}nextSignificantParent(){let t=this;for(;t.type.isAnonymous&&t._parent;)t=t._parent;return t}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get tree(){return this._tree}toTree(){return this._tree}toString(){return this._tree.toString()}}function da(t,e,i,n){let s=t.cursor(),r=[];if(!s.firstChild())return r;if(null!=i)for(let t=!1;!t;)if(t=s.type.is(i),!s.nextSibling())return r;for(;;){if(null!=n&&s.type.is(n))return r;if(s.type.is(e)&&r.push(s.node),!s.nextSibling())return null==n?r:[]}}function pa(t,e,i=e.length-1){for(let n=t.parent;i>=0;n=n.parent){if(!n)return!1;if(!n.type.isAnonymous){if(e[i]&&e[i]!=n.name)return!1;i--}}return!0}class Oa{constructor(t,e,i,n){this.parent=t,this.buffer=e,this.index=i,this.start=n}}class ga extends fa{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(t,e,i){super(),this.context=t,this._parent=e,this.index=i,this.type=t.buffer.set.types[t.buffer.buffer[i]]}child(t,e,i){let{buffer:n}=this.context,s=n.findChild(this.index+4,n.buffer[this.index+3],t,e-this.context.start,i);return s<0?null:new ga(this.context,this,s)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(t){return this.child(1,t,2)}childBefore(t){return this.child(-1,t,-2)}enter(t,e,i=0){if(i&ra.ExcludeBuffers)return null;let{buffer:n}=this.context,s=n.findChild(this.index+4,n.buffer[this.index+3],e>0?1:-1,t-this.context.start,e);return s<0?null:new ga(this.context,this,s)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(t){return this._parent?null:this.context.parent.nextChild(this.context.index+t,t,0,4)}get nextSibling(){let{buffer:t}=this.context,e=t.buffer[this.index+3];return e<(this._parent?t.buffer[this._parent.index+3]:t.buffer.length)?new ga(this.context,this._parent,e):this.externalSibling(1)}get prevSibling(){let{buffer:t}=this.context,e=this._parent?this._parent.index+4:0;return this.index==e?this.externalSibling(-1):new ga(this.context,this._parent,t.findChild(e,this.index,-1,0,4))}get tree(){return null}toTree(){let t=[],e=[],{buffer:i}=this.context,n=this.index+4,s=i.buffer[this.index+3];if(s>n){let r=i.buffer[this.index+1];t.push(i.slice(n,s,r)),e.push(0)}return new oa(this.type,t,e,this.to-this.from)}toString(){return this.context.buffer.childString(this.index)}}function ma(t){if(!t.length)return null;let e=0,i=t[0];for(let n=1;n<t.length;n++){let s=t[n];(s.from>i.from||s.to<i.to)&&(i=s,e=n)}let n=i instanceof ua&&i.index<0?null:i.parent,s=t.slice();return n?s[e]=n:s.splice(e,1),new wa(s,i)}class wa{constructor(t,e){this.heads=t,this.node=e}get next(){return ma(this.heads)}}class va{get name(){return this.type.name}constructor(t,e=0){if(this.mode=e,this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,t instanceof ua)this.yieldNode(t);else{this._tree=t.context.parent,this.buffer=t.context;for(let e=t._parent;e;e=e._parent)this.stack.unshift(e.index);this.bufferNode=t,this.yieldBuf(t.index)}}yieldNode(t){return!!t&&(this._tree=t,this.type=t.type,this.from=t.from,this.to=t.to,!0)}yieldBuf(t,e){this.index=t;let{start:i,buffer:n}=this.buffer;return this.type=e||n.set.types[n.buffer[t]],this.from=i+n.buffer[t+1],this.to=i+n.buffer[t+2],!0}yield(t){return!!t&&(t instanceof ua?(this.buffer=null,this.yieldNode(t)):(this.buffer=t.context,this.yieldBuf(t.index,t.type)))}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(t,e,i){if(!this.buffer)return this.yield(this._tree.nextChild(t<0?this._tree._tree.children.length-1:0,t,e,i,this.mode));let{buffer:n}=this.buffer,s=n.findChild(this.index+4,n.buffer[this.index+3],t,e-this.buffer.start,i);return!(s<0)&&(this.stack.push(this.index),this.yieldBuf(s))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(t){return this.enterChild(1,t,2)}childBefore(t){return this.enterChild(-1,t,-2)}enter(t,e,i=this.mode){return this.buffer?!(i&ra.ExcludeBuffers)&&this.enterChild(1,t,e):this.yield(this._tree.enter(t,e,i))}parent(){if(!this.buffer)return this.yieldNode(this.mode&ra.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let t=this.mode&ra.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(t)}sibling(t){if(!this.buffer)return!!this._tree._parent&&this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+t,t,0,4,this.mode));let{buffer:e}=this.buffer,i=this.stack.length-1;if(t<0){let t=i<0?0:this.stack[i]+4;if(this.index!=t)return this.yieldBuf(e.findChild(t,this.index,-1,0,4))}else{let t=e.buffer[this.index+3];if(t<(i<0?e.buffer.length:e.buffer[this.stack[i]+3]))return this.yieldBuf(t)}return i<0&&this.yield(this.buffer.parent.nextChild(this.buffer.index+t,t,0,4,this.mode))}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(t){let e,i,{buffer:n}=this;if(n){if(t>0){if(this.index<n.buffer.buffer.length)return!1}else for(let t=0;t<this.index;t++)if(n.buffer.buffer[t+3]<this.index)return!1;({index:e,parent:i}=n)}else({index:e,_parent:i}=this._tree);for(;i;({index:e,_parent:i}=i))if(e>-1)for(let n=e+t,s=t<0?-1:i._tree.children.length;n!=s;n+=t){let t=i._tree.children[n];if(this.mode&ra.IncludeAnonymous||t instanceof la||!t.type.isAnonymous||ba(t))return!1}return!0}move(t,e){if(e&&this.enterChild(t,0,4))return!0;for(;;){if(this.sibling(t))return!0;if(this.atLastNode(t)||!this.parent())return!1}}next(t=!0){return this.move(1,t)}prev(t=!0){return this.move(-1,t)}moveTo(t,e=0){for(;(this.from==this.to||(e<1?this.from>=t:this.from>t)||(e>-1?this.to<=t:this.to<t))&&this.parent(););for(;this.enterChild(1,t,e););return this}get node(){if(!this.buffer)return this._tree;let t=this.bufferNode,e=null,i=0;if(t&&t.context==this.buffer)t:for(let n=this.index,s=this.stack.length;s>=0;){for(let r=t;r;r=r._parent)if(r.index==n){if(n==this.index)return r;e=r,i=s+1;break t}n=this.stack[--s]}for(let t=i;t<this.stack.length;t++)e=new ga(this.buffer,e,this.stack[t]);return this.bufferNode=new ga(this.buffer,e,this.index)}get tree(){return this.buffer?null:this._tree._tree}iterate(t,e){for(let i=0;;){let n=!1;if(this.type.isAnonymous||!1!==t(this)){if(this.firstChild()){i++;continue}this.type.isAnonymous||(n=!0)}for(;n&&e&&e(this),n=this.type.isAnonymous,!this.nextSibling();){if(!i)return;this.parent(),i--,n=!0}}}matchContext(t){if(!this.buffer)return pa(this.node,t);let{buffer:e}=this.buffer,{types:i}=e.set;for(let n=t.length-1,s=this.stack.length-1;n>=0;s--){if(s<0)return pa(this.node,t,n);let r=i[e.buffer[this.stack[s]]];if(!r.isAnonymous){if(t[n]&&t[n]!=r.name)return!1;n--}}return!0}}function ba(t){return t.children.some((t=>t instanceof la||!t.type.isAnonymous||ba(t)))}const ya=new WeakMap;function Sa(t,e){if(!t.isAnonymous||e instanceof la||e.type!=t)return 1;let i=ya.get(e);if(null==i){i=1;for(let n of e.children){if(n.type!=t||!(n instanceof oa)){i=1;break}i+=Sa(t,n)}ya.set(e,i)}return i}function xa(t,e,i,n,s,r,o,a,l){let h=0;for(let i=n;i<s;i++)h+=Sa(t,e[i]);let c=Math.ceil(1.5*h/8),f=[],u=[];return function e(i,n,s,o,a){for(let h=s;h<o;){let s=h,d=n[h],p=Sa(t,i[h]);for(h++;h<o;h++){let e=Sa(t,i[h]);if(p+e>=c)break;p+=e}if(h==s+1){if(p>c){let t=i[s];e(t.children,t.positions,0,t.children.length,n[s]+a);continue}f.push(i[s])}else{let e=n[h-1]+i[h-1].length-d;f.push(xa(t,i,n,s,h,d,e,null,l))}u.push(d+a-r)}}(e,i,n,s,0),(a||l)(f,u,o)}class ka{constructor(){this.map=new WeakMap}setBuffer(t,e,i){let n=this.map.get(t);n||this.map.set(t,n=new Map),n.set(e,i)}getBuffer(t,e){let i=this.map.get(t);return i&&i.get(e)}set(t,e){t instanceof ga?this.setBuffer(t.context.buffer,t.index,e):t instanceof ua&&this.map.set(t.tree,e)}get(t){return t instanceof ga?this.getBuffer(t.context.buffer,t.index):t instanceof ua?this.map.get(t.tree):void 0}cursorSet(t,e){t.buffer?this.setBuffer(t.buffer.buffer,t.index,e):this.map.set(t.tree,e)}cursorGet(t){return t.buffer?this.getBuffer(t.buffer.buffer,t.index):this.map.get(t.tree)}}class Qa{constructor(t,e,i,n,s=!1,r=!1){this.from=t,this.to=e,this.tree=i,this.offset=n,this.open=(s?1:0)|(r?2:0)}get openStart(){return(1&this.open)>0}get openEnd(){return(2&this.open)>0}static addTree(t,e=[],i=!1){let n=[new Qa(0,t.length,t,0,!1,i)];for(let i of e)i.to>t.length&&n.push(i);return n}static applyChanges(t,e,i=128){if(!e.length)return t;let n=[],s=1,r=t.length?t[0]:null;for(let o=0,a=0,l=0;;o++){let h=o<e.length?e[o]:null,c=h?h.fromA:1e9;if(c-a>=i)for(;r&&r.from<c;){let e=r;if(a>=e.from||c<=e.to||l){let t=Math.max(e.from,a)-l,i=Math.min(e.to,c)-l;e=t>=i?null:new Qa(t,i,e.tree,e.offset+l,o>0,!!h)}if(e&&n.push(e),r.to>c)break;r=s<t.length?t[s++]:null}if(!h)break;a=h.toA,l=h.toA-h.toB}return n}}class $a{startParse(t,e,i){return"string"==typeof t&&(t=new Pa(t)),i=i?i.length?i.map((t=>new Fo(t.from,t.to))):[new Fo(0,0)]:[new Fo(0,t.length)],this.createParse(t,e||[],i)}parse(t,e,i){let n=this.startParse(t,e,i);for(;;){let t=n.advance();if(t)return t}}}class Pa{constructor(t){this.string=t}get length(){return this.string.length}chunk(t){return this.string.slice(t)}get lineChunks(){return!1}read(t,e){return this.string.slice(t,e)}}new Jo({perNode:!0});let Za=0;class Ca{constructor(t,e,i){this.set=t,this.base=e,this.modified=i,this.id=Za++}static define(t){if(null==t?void 0:t.base)throw new Error("Can not derive from a modified tag");let e=new Ca([],null,[]);if(e.set.push(e),t)for(let i of t.set)e.set.push(i);return e}static defineModifier(){let t=new Aa;return e=>e.modified.indexOf(t)>-1?e:Aa.get(e.base||e,e.modified.concat(t).sort(((t,e)=>t.id-e.id)))}}let Ta=0;class Aa{constructor(){this.instances=[],this.id=Ta++}static get(t,e){if(!e.length)return t;let i=e[0].instances.find((i=>{return i.base==t&&(n=e,s=i.modified,n.length==s.length&&n.every(((t,e)=>t==s[e])));var n,s}));if(i)return i;let n=[],s=new Ca(n,t,e);for(let t of e)t.instances.push(s);let r=function(t){let e=[[]];for(let i=0;i<t.length;i++)for(let n=0,s=e.length;n<s;n++)e.push(e[n].concat(t[i]));return e.sort(((t,e)=>e.length-t.length))}(e);for(let e of t.set)if(!e.modified.length)for(let t of r)n.push(Aa.get(e,t));return s}}function Ra(t){let e=Object.create(null);for(let i in t){let n=t[i];Array.isArray(n)||(n=[n]);for(let t of i.split(" "))if(t){let i=[],s=2,r=t;for(let e=0;;){if("..."==r&&e>0&&e+3==t.length){s=1;break}let n=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(r);if(!n)throw new RangeError("Invalid path: "+t);if(i.push("*"==n[0]?"":'"'==n[0][0]?JSON.parse(n[0]):n[0]),e+=n[0].length,e==t.length)break;let o=t[e++];if(e==t.length&&"!"==o){s=0;break}if("/"!=o)throw new RangeError("Invalid path: "+t);r=t.slice(e)}let o=i.length-1,a=i[o];if(!a)throw new RangeError("Invalid path: "+t);let l=new Ya(n,s,o>0?i.slice(0,o):null);e[a]=l.sort(e[a])}}return Xa.add(e)}const Xa=new Jo;class Ya{constructor(t,e,i,n){this.tags=t,this.mode=e,this.context=i,this.next=n}get opaque(){return 0==this.mode}get inherit(){return 1==this.mode}sort(t){return!t||t.depth<this.depth?(this.next=t,this):(t.next=this.sort(t.next),t)}get depth(){return this.context?this.context.length:0}}function Wa(t,e){let i=Object.create(null);for(let e of t)if(Array.isArray(e.tag))for(let t of e.tag)i[t.id]=e.class;else i[e.tag.id]=e.class;let{scope:n,all:s=null}=e||{};return{style:t=>{let e=s;for(let n of t)for(let t of n.set){let n=i[t.id];if(n){e=e?e+" "+n:n;break}}return e},scope:n}}function Ma(t,e,i,n=0,s=t.length){let r=new ja(n,Array.isArray(e)?e:[e],i);r.highlightRange(t.cursor(),n,s,"",r.highlighters),r.flush(s)}Ya.empty=new Ya([],2,null);class ja{constructor(t,e,i){this.at=t,this.highlighters=e,this.span=i,this.class=""}startSpan(t,e){e!=this.class&&(this.flush(t),t>this.at&&(this.at=t),this.class=e)}flush(t){t>this.at&&this.class&&this.span(this.at,t,this.class)}highlightRange(t,e,i,n,s){let{type:r,from:o,to:a}=t;if(o>=i||a<=e)return;r.isTop&&(s=this.highlighters.filter((t=>!t.scope||t.scope(r))));let l=n,h=Da(t)||Ya.empty,c=function(t,e){let i=null;for(let n of t){let t=n.style(e);t&&(i=i?i+" "+t:t)}return i}(s,h.tags);if(c&&(l&&(l+=" "),l+=c,1==h.mode&&(n+=(n?" ":"")+c)),this.startSpan(Math.max(e,o),l),h.opaque)return;let f=t.tree&&t.tree.prop(Jo.mounted);if(f&&f.overlay){let r=t.node.enter(f.overlay[0].from+o,1),h=this.highlighters.filter((t=>!t.scope||t.scope(f.tree.type))),c=t.firstChild();for(let u=0,d=o;;u++){let p=u<f.overlay.length?f.overlay[u]:null,O=p?p.from+o:a,g=Math.max(e,d),m=Math.min(i,O);if(g<m&&c)for(;t.from<m&&(this.highlightRange(t,g,m,n,s),this.startSpan(Math.min(m,t.to),l),!(t.to>=O)&&t.nextSibling()););if(!p||O>i)break;d=p.to+o,d>e&&(this.highlightRange(r.cursor(),Math.max(e,p.from+o),Math.min(i,d),"",h),this.startSpan(Math.min(i,d),l))}c&&t.parent()}else if(t.firstChild()){f&&(n="");do{if(!(t.to<=e)){if(t.from>=i)break;this.highlightRange(t,e,i,n,s),this.startSpan(Math.min(i,t.to),l)}}while(t.nextSibling());t.parent()}}}function Da(t){let e=t.type.prop(Xa);for(;e&&e.context&&!t.matchContext(e.context);)e=e.next;return e||null}const Ea=Ca.define,qa=Ea(),_a=Ea(),Va=Ea(_a),Ia=Ea(_a),za=Ea(),Ba=Ea(za),Ga=Ea(za),La=Ea(),Na=Ea(La),Ua=Ea(),Ha=Ea(),Fa=Ea(),Ja=Ea(Fa),Ka=Ea(),tl={comment:qa,lineComment:Ea(qa),blockComment:Ea(qa),docComment:Ea(qa),name:_a,variableName:Ea(_a),typeName:Va,tagName:Ea(Va),propertyName:Ia,attributeName:Ea(Ia),className:Ea(_a),labelName:Ea(_a),namespace:Ea(_a),macroName:Ea(_a),literal:za,string:Ba,docString:Ea(Ba),character:Ea(Ba),attributeValue:Ea(Ba),number:Ga,integer:Ea(Ga),float:Ea(Ga),bool:Ea(za),regexp:Ea(za),escape:Ea(za),color:Ea(za),url:Ea(za),keyword:Ua,self:Ea(Ua),null:Ea(Ua),atom:Ea(Ua),unit:Ea(Ua),modifier:Ea(Ua),operatorKeyword:Ea(Ua),controlKeyword:Ea(Ua),definitionKeyword:Ea(Ua),moduleKeyword:Ea(Ua),operator:Ha,derefOperator:Ea(Ha),arithmeticOperator:Ea(Ha),logicOperator:Ea(Ha),bitwiseOperator:Ea(Ha),compareOperator:Ea(Ha),updateOperator:Ea(Ha),definitionOperator:Ea(Ha),typeOperator:Ea(Ha),controlOperator:Ea(Ha),punctuation:Fa,separator:Ea(Fa),bracket:Ja,angleBracket:Ea(Ja),squareBracket:Ea(Ja),paren:Ea(Ja),brace:Ea(Ja),content:La,heading:Na,heading1:Ea(Na),heading2:Ea(Na),heading3:Ea(Na),heading4:Ea(Na),heading5:Ea(Na),heading6:Ea(Na),contentSeparator:Ea(La),list:Ea(La),quote:Ea(La),emphasis:Ea(La),strong:Ea(La),link:Ea(La),monospace:Ea(La),strikethrough:Ea(La),inserted:Ea(),deleted:Ea(),changed:Ea(),invalid:Ea(),meta:Ka,documentMeta:Ea(Ka),annotation:Ea(Ka),processingInstruction:Ea(Ka),definition:Ca.defineModifier(),constant:Ca.defineModifier(),function:Ca.defineModifier(),standard:Ca.defineModifier(),local:Ca.defineModifier(),special:Ca.defineModifier()},el=Wa([{tag:tl.link,class:"tok-link"},{tag:tl.heading,class:"tok-heading"},{tag:tl.emphasis,class:"tok-emphasis"},{tag:tl.strong,class:"tok-strong"},{tag:tl.keyword,class:"tok-keyword"},{tag:tl.atom,class:"tok-atom"},{tag:tl.bool,class:"tok-bool"},{tag:tl.url,class:"tok-url"},{tag:tl.labelName,class:"tok-labelName"},{tag:tl.inserted,class:"tok-inserted"},{tag:tl.deleted,class:"tok-deleted"},{tag:tl.literal,class:"tok-literal"},{tag:tl.string,class:"tok-string"},{tag:tl.number,class:"tok-number"},{tag:[tl.regexp,tl.escape,tl.special(tl.string)],class:"tok-string2"},{tag:tl.variableName,class:"tok-variableName"},{tag:tl.local(tl.variableName),class:"tok-variableName tok-local"},{tag:tl.definition(tl.variableName),class:"tok-variableName tok-definition"},{tag:tl.special(tl.variableName),class:"tok-variableName2"},{tag:tl.definition(tl.propertyName),class:"tok-propertyName tok-definition"},{tag:tl.typeName,class:"tok-typeName"},{tag:tl.namespace,class:"tok-namespace"},{tag:tl.className,class:"tok-className"},{tag:tl.macroName,class:"tok-macroName"},{tag:tl.propertyName,class:"tok-propertyName"},{tag:tl.operator,class:"tok-operator"},{tag:tl.comment,class:"tok-comment"},{tag:tl.meta,class:"tok-meta"},{tag:tl.invalid,class:"tok-invalid"},{tag:tl.punctuation,class:"tok-punctuation"}]);var il,nl=Object.freeze({__proto__:null,Tag:Ca,classHighlighter:el,getStyleTags:Da,highlightCode:function(t,e,i,n,s,r=0,o=t.length){let a=r;function l(e,i){if(!(e<=a)){for(let r=t.slice(a,e),o=0;;){let t=r.indexOf("\n",o),e=t<0?r.length:t;if(e>o&&n(r.slice(o,e),i),t<0)break;s(),o=t+1}a=e}}Ma(e,i,((t,e,i)=>{l(t,""),l(e,i)}),r,o),l(o,"")},highlightTree:Ma,styleTags:Ra,tagHighlighter:Wa,tags:tl});const sl=new Jo;function rl(t){return j.define({combine:t?e=>e.concat(t):void 0})}const ol=new Jo;class al{constructor(t,e,i=[],n=""){this.data=t,this.name=n,Qt.prototype.hasOwnProperty("tree")||Object.defineProperty(Qt.prototype,"tree",{get(){return cl(this)}}),this.parser=e,this.extension=[bl.of(this),Qt.languageData.of(((t,e,i)=>{let n=ll(t,e,i),s=n.type.prop(sl);if(!s)return[];let r=t.facet(s),o=n.type.prop(ol);if(o){let s=n.resolve(e-n.from,i);for(let e of o)if(e.test(s,t)){let i=t.facet(e.facet);return"replace"==e.type?i:i.concat(r)}}return r}))].concat(i)}isActiveAt(t,e,i=-1){return ll(t,e,i).type.prop(sl)==this.data}findRegions(t){let e=t.facet(bl);if((null==e?void 0:e.data)==this.data)return[{from:0,to:t.doc.length}];if(!e||!e.allowsNesting)return[];let i=[],n=(t,e)=>{if(t.prop(sl)==this.data)return void i.push({from:e,to:e+t.length});let s=t.prop(Jo.mounted);if(s){if(s.tree.prop(sl)==this.data){if(s.overlay)for(let t of s.overlay)i.push({from:t.from+e,to:t.to+e});else i.push({from:e,to:e+t.length});return}if(s.overlay){let t=i.length;if(n(s.tree,s.overlay[0].from+e),i.length>t)return}}for(let i=0;i<t.children.length;i++){let s=t.children[i];s instanceof oa&&n(s,t.positions[i]+e)}};return n(cl(t),0),i}get allowsNesting(){return!0}}function ll(t,e,i){let n=t.facet(bl),s=cl(t).topNode;if(!n||n.allowsNesting)for(let t=s;t;t=t.enter(e,i,ra.ExcludeBuffers))t.type.isTop&&(s=t);return s}al.setState=dt.define();class hl extends al{constructor(t,e,i){super(t,e,[],i),this.parser=e}static define(t){let e=rl(t.languageData);return new hl(e,t.parser.configure({props:[sl.add((t=>t.isTop?e:void 0))]}),t.name)}configure(t,e){return new hl(this.data,this.parser.configure(t),e||this.name)}get allowsNesting(){return this.parser.hasWrappers()}}function cl(t){let e=t.field(al.state,!1);return e?e.tree:oa.empty}function fl(t,e,i=50){var n;let s=null===(n=t.field(al.state,!1))||void 0===n?void 0:n.context;if(!s)return null;let r=s.viewport;s.updateViewport({from:0,to:e});let o=s.isDone(e)||s.work(i,e)?s.tree:null;return s.updateViewport(r),o}class ul{constructor(t){this.doc=t,this.cursorPos=0,this.string="",this.cursor=t.iter()}get length(){return this.doc.length}syncTo(t){return this.string=this.cursor.next(t-this.cursorPos).value,this.cursorPos=t+this.string.length,this.cursorPos-this.string.length}chunk(t){return this.syncTo(t),this.string}get lineChunks(){return!0}read(t,e){let i=this.cursorPos-this.string.length;return t<i||e>=this.cursorPos?this.doc.sliceString(t,e):this.string.slice(t-i,e-i)}}let dl=null;class pl{constructor(t,e,i=[],n,s,r,o,a){this.parser=t,this.state=e,this.fragments=i,this.tree=n,this.treeLen=s,this.viewport=r,this.skipped=o,this.scheduleOn=a,this.parse=null,this.tempSkipped=[]}static create(t,e,i){return new pl(t,e,[],oa.empty,0,i,[],null)}startParse(){return this.parser.startParse(new ul(this.state.doc),this.fragments)}work(t,e){return null!=e&&e>=this.state.doc.length&&(e=void 0),this.tree!=oa.empty&&this.isDone(null!=e?e:this.state.doc.length)?(this.takeTree(),!0):this.withContext((()=>{var i;if("number"==typeof t){let e=Date.now()+t;t=()=>Date.now()>e}for(this.parse||(this.parse=this.startParse()),null!=e&&(null==this.parse.stoppedAt||this.parse.stoppedAt>e)&&e<this.state.doc.length&&this.parse.stopAt(e);;){let n=this.parse.advance();if(n){if(this.fragments=this.withoutTempSkipped(Qa.addTree(n,this.fragments,null!=this.parse.stoppedAt)),this.treeLen=null!==(i=this.parse.stoppedAt)&&void 0!==i?i:this.state.doc.length,this.tree=n,this.parse=null,!(this.treeLen<(null!=e?e:this.state.doc.length)))return!0;this.parse=this.startParse()}if(t())return!1}}))}takeTree(){let t,e;this.parse&&(t=this.parse.parsedPos)>=this.treeLen&&((null==this.parse.stoppedAt||this.parse.stoppedAt>t)&&this.parse.stopAt(t),this.withContext((()=>{for(;!(e=this.parse.advance()););})),this.treeLen=t,this.tree=e,this.fragments=this.withoutTempSkipped(Qa.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(t){let e=dl;dl=this;try{return t()}finally{dl=e}}withoutTempSkipped(t){for(let e;e=this.tempSkipped.pop();)t=Ol(t,e.from,e.to);return t}changes(t,e){let{fragments:i,tree:n,treeLen:s,viewport:r,skipped:o}=this;if(this.takeTree(),!t.empty){let e=[];if(t.iterChangedRanges(((t,i,n,s)=>e.push({fromA:t,toA:i,fromB:n,toB:s}))),i=Qa.applyChanges(i,e),n=oa.empty,s=0,r={from:t.mapPos(r.from,-1),to:t.mapPos(r.to,1)},this.skipped.length){o=[];for(let e of this.skipped){let i=t.mapPos(e.from,1),n=t.mapPos(e.to,-1);i<n&&o.push({from:i,to:n})}}}return new pl(this.parser,e,i,n,s,r,o,this.scheduleOn)}updateViewport(t){if(this.viewport.from==t.from&&this.viewport.to==t.to)return!1;this.viewport=t;let e=this.skipped.length;for(let e=0;e<this.skipped.length;e++){let{from:i,to:n}=this.skipped[e];i<t.to&&n>t.from&&(this.fragments=Ol(this.fragments,i,n),this.skipped.splice(e--,1))}return!(this.skipped.length>=e)&&(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(t,e){this.skipped.push({from:t,to:e})}static getSkippingParser(t){return new class extends $a{createParse(e,i,n){let s=n[0].from,r=n[n.length-1].to;return{parsedPos:s,advance(){let e=dl;if(e){for(let t of n)e.tempSkipped.push(t);t&&(e.scheduleOn=e.scheduleOn?Promise.all([e.scheduleOn,t]):t)}return this.parsedPos=r,new oa(ea.none,[],[],r-s)},stoppedAt:null,stopAt(){}}}}}isDone(t){t=Math.min(t,this.state.doc.length);let e=this.fragments;return this.treeLen>=t&&e.length&&0==e[0].from&&e[0].to>=t}static get(){return dl}}function Ol(t,e,i){return Qa.applyChanges(t,[{fromA:e,toA:i,fromB:e,toB:i}])}class gl{constructor(t){this.context=t,this.tree=t.tree}apply(t){if(!t.docChanged&&this.tree==this.context.tree)return this;let e=this.context.changes(t.changes,t.state),i=this.context.treeLen==t.startState.doc.length?void 0:Math.max(t.changes.mapPos(this.context.treeLen),e.viewport.to);return e.work(20,i)||e.takeTree(),new gl(e)}static init(t){let e=Math.min(3e3,t.doc.length),i=pl.create(t.facet(bl).parser,t,{from:0,to:e});return i.work(20,e)||i.takeTree(),new gl(i)}}al.state=z.define({create:gl.init,update(t,e){for(let t of e.effects)if(t.is(al.setState))return t.value;return e.startState.facet(bl)!=e.state.facet(bl)?gl.init(e.state):t.apply(e)}});let ml=t=>{let e=setTimeout((()=>t()),500);return()=>clearTimeout(e)};"undefined"!=typeof requestIdleCallback&&(ml=t=>{let e=-1,i=setTimeout((()=>{e=requestIdleCallback(t,{timeout:400})}),100);return()=>e<0?clearTimeout(i):cancelIdleCallback(e)});const wl="undefined"!=typeof navigator&&(null===(il=navigator.scheduling)||void 0===il?void 0:il.isInputPending)?()=>navigator.scheduling.isInputPending():null,vl=Ni.fromClass(class{constructor(t){this.view=t,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(t){let e=this.view.state.field(al.state).context;(e.updateViewport(t.view.viewport)||this.view.viewport.to>e.treeLen)&&this.scheduleWork(),(t.docChanged||t.selectionSet)&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(e)}scheduleWork(){if(this.working)return;let{state:t}=this.view,e=t.field(al.state);e.tree==e.context.tree&&e.context.isDone(t.doc.length)||(this.working=ml(this.work))}work(t){this.working=null;let e=Date.now();if(this.chunkEnd<e&&(this.chunkEnd<0||this.view.hasFocus)&&(this.chunkEnd=e+3e4,this.chunkBudget=3e3),this.chunkBudget<=0)return;let{state:i,viewport:{to:n}}=this.view,s=i.field(al.state);if(s.tree==s.context.tree&&s.context.isDone(n+1e5))return;let r=Date.now()+Math.min(this.chunkBudget,100,t&&!wl?Math.max(25,t.timeRemaining()-5):1e9),o=s.context.treeLen<n&&i.doc.length>n+1e3,a=s.context.work((()=>wl&&wl()||Date.now()>r),n+(o?0:1e5));this.chunkBudget-=Date.now()-e,(a||this.chunkBudget<=0)&&(s.context.takeTree(),this.view.dispatch({effects:al.setState.of(new gl(s.context))})),this.chunkBudget>0&&(!a||o)&&this.scheduleWork(),this.checkAsyncSchedule(s.context)}checkAsyncSchedule(t){t.scheduleOn&&(this.workScheduled++,t.scheduleOn.then((()=>this.scheduleWork())).catch((t=>zi(this.view.state,t))).then((()=>this.workScheduled--)),t.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),bl=j.define({combine:t=>t.length?t[0]:null,enables:t=>[al.state,vl,Gs.contentAttributes.compute([t],(e=>{let i=e.facet(t);return i&&i.name?{"data-language":i.name}:{}}))]});class yl{constructor(t,e=[]){this.language=t,this.support=e,this.extension=[t,e]}}class Sl{constructor(t,e,i,n,s,r=void 0){this.name=t,this.alias=e,this.extensions=i,this.filename=n,this.loadFunc=s,this.support=r,this.loading=null}load(){return this.loading||(this.loading=this.loadFunc().then((t=>this.support=t),(t=>{throw this.loading=null,t})))}static of(t){let{load:e,support:i}=t;if(!e){if(!i)throw new RangeError("Must pass either 'load' or 'support' to LanguageDescription.of");e=()=>Promise.resolve(i)}return new Sl(t.name,(t.alias||[]).concat(t.name).map((t=>t.toLowerCase())),t.extensions||[],t.filename,e,i)}static matchFilename(t,e){for(let i of t)if(i.filename&&i.filename.test(e))return i;let i=/\.([^.]+)$/.exec(e);if(i)for(let e of t)if(e.extensions.indexOf(i[1])>-1)return e;return null}static matchLanguageName(t,e,i=!0){e=e.toLowerCase();for(let i of t)if(i.alias.some((t=>t==e)))return i;if(i)for(let i of t)for(let t of i.alias){let n=e.indexOf(t);if(n>-1&&(t.length>2||!/\w/.test(e[n-1])&&!/\w/.test(e[n+t.length])))return i}return null}}const xl=j.define(),kl=j.define({combine:t=>{if(!t.length)return" ";let e=t[0];if(!e||/\S/.test(e)||Array.from(e).some((t=>t!=e[0])))throw new Error("Invalid indent unit: "+JSON.stringify(t[0]));return e}});function Ql(t){let e=t.facet(kl);return 9==e.charCodeAt(0)?t.tabSize*e.length:e.length}function $l(t,e){let i="",n=t.tabSize,s=t.facet(kl)[0];if("\t"==s){for(;e>=n;)i+="\t",e-=n;s=" "}for(let t=0;t<e;t++)i+=s;return i}function Pl(t,e){t instanceof Qt&&(t=new Zl(t));for(let i of t.state.facet(xl)){let n=i(t,e);if(void 0!==n)return n}let i=cl(t.state);return i.length>=e?function(t,e,i){let n=e.resolveStack(i),s=n.node.enterUnfinishedNodesBefore(i);if(s!=n.node){let t=[];for(let e=s;e!=n.node;e=e.parent)t.push(e);for(let e=t.length-1;e>=0;e--)n={node:t[e],next:n}}return Tl(n,t,i)}(t,i,e):null}class Zl{constructor(t,e={}){this.state=t,this.options=e,this.unit=Ql(t)}lineAt(t,e=1){let i=this.state.doc.lineAt(t),{simulateBreak:n,simulateDoubleBreak:s}=this.options;return null!=n&&n>=i.from&&n<=i.to?s&&n==t?{text:"",from:t}:(e<0?n<t:n<=t)?{text:i.text.slice(n-i.from),from:n}:{text:i.text.slice(0,n-i.from),from:i.from}:i}textAfterPos(t,e=1){if(this.options.simulateDoubleBreak&&t==this.options.simulateBreak)return"";let{text:i,from:n}=this.lineAt(t,e);return i.slice(t-n,Math.min(i.length,t+100-n))}column(t,e=1){let{text:i,from:n}=this.lineAt(t,e),s=this.countColumn(i,t-n),r=this.options.overrideIndentation?this.options.overrideIndentation(n):-1;return r>-1&&(s+=r-this.countColumn(i,i.search(/\S|$/))),s}countColumn(t,e=t.length){return It(t,this.state.tabSize,e)}lineIndent(t,e=1){let{text:i,from:n}=this.lineAt(t,e),s=this.options.overrideIndentation;if(s){let t=s(n);if(t>-1)return t}return this.countColumn(i,i.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}}const Cl=new Jo;function Tl(t,e,i){for(let n=t;n;n=n.next){let t=Al(n.node);if(t)return t(Xl.create(e,i,n))}return 0}function Al(t){let e=t.type.prop(Cl);if(e)return e;let i,n=t.firstChild;if(n&&(i=n.type.prop(Jo.closedBy))){let e=t.lastChild,n=e&&i.indexOf(e.name)>-1;return t=>Ml(t,!0,1,void 0,n&&!function(t){return t.pos==t.options.simulateBreak&&t.options.simulateDoubleBreak}(t)?e.from:void 0)}return null==t.parent?Rl:null}function Rl(){return 0}class Xl extends Zl{constructor(t,e,i){super(t.state,t.options),this.base=t,this.pos=e,this.context=i}get node(){return this.context.node}static create(t,e,i){return new Xl(t,e,i)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(t){let e=this.state.doc.lineAt(t.from);for(;;){let i=t.resolve(e.from);for(;i.parent&&i.parent.from==i.from;)i=i.parent;if(Yl(i,t))break;e=this.state.doc.lineAt(i.from)}return this.lineIndent(e.from)}continue(){return Tl(this.context.next,this.base,this.pos)}}function Yl(t,e){for(let i=e;i;i=i.parent)if(t==i)return!0;return!1}function Wl({closing:t,align:e=!0,units:i=1}){return n=>Ml(n,e,i,t)}function Ml(t,e,i,n,s){let r=t.textAfter,o=r.match(/^\s*/)[0].length,a=n&&r.slice(o,o+n.length)==n||s==t.pos+o,l=e?function(t){let e=t.node,i=e.childAfter(e.from),n=e.lastChild;if(!i)return null;let s=t.options.simulateBreak,r=t.state.doc.lineAt(i.from),o=null==s||s<=r.from?r.to:Math.min(r.to,s);for(let t=i.to;;){let s=e.childAfter(t);if(!s||s==n)return null;if(!s.type.isSkipped)return s.from<o?i:null;t=s.to}}(t):null;return l?a?t.column(l.from):t.column(l.to):t.baseIndent+(a?0:t.unit*i)}const jl=t=>t.baseIndent;function Dl({except:t,units:e=1}={}){return i=>{let n=t&&t.test(i.textAfter);return i.baseIndent+(n?0:e*i.unit)}}function El(){return Qt.transactionFilter.of((t=>{if(!t.docChanged||!t.isUserEvent("input.type")&&!t.isUserEvent("input.complete"))return t;let e=t.startState.languageDataAt("indentOnInput",t.startState.selection.main.head);if(!e.length)return t;let i=t.newDoc,{head:n}=t.newSelection.main,s=i.lineAt(n);if(n>s.from+200)return t;let r=i.sliceString(s.from,n);if(!e.some((t=>t.test(r))))return t;let{state:o}=t,a=-1,l=[];for(let{head:t}of o.selection.ranges){let e=o.doc.lineAt(t);if(e.from==a)continue;a=e.from;let i=Pl(o,e.from);if(null==i)continue;let n=/^\s*/.exec(e.text)[0],s=$l(o,i);n!=s&&l.push({from:e.from,to:e.from+n.length,insert:s})}return l.length?[t,{changes:l,sequential:!0}]:t}))}const ql=j.define(),_l=new Jo;function Vl(t){let e=t.firstChild,i=t.lastChild;return e&&e.to<i.from?{from:e.to,to:i.type.isError?t.to:i.from}:null}function Il(t){let e=t.lastChild;return e&&e.to==t.to&&e.type.isError}function zl(t,e,i){for(let n of t.facet(ql)){let s=n(t,e,i);if(s)return s}return function(t,e,i){let n=cl(t);if(n.length<i)return null;let s=null;for(let r=n.resolveStack(i,1);r;r=r.next){let o=r.node;if(o.to<=i||o.from>i)continue;if(s&&o.from<e)break;let a=o.type.prop(_l);if(a&&(o.to<n.length-50||n.length==t.doc.length||!Il(o))){let n=a(o,t);n&&n.from<=i&&n.from>=e&&n.to>i&&(s=n)}}return s}(t,e,i)}function Bl(t,e){let i=e.mapPos(t.from,1),n=e.mapPos(t.to,-1);return i>=n?void 0:{from:i,to:n}}const Gl=dt.define({map:Bl}),Ll=dt.define({map:Bl});function Nl(t){let e=[];for(let{head:i}of t.state.selection.ranges)e.some((t=>t.from<=i&&t.to>=i))||e.push(t.lineBlockAt(i));return e}const Ul=z.define({create:()=>si.none,update(t,e){t=t.map(e.changes);for(let i of e.effects)if(i.is(Gl)&&!Fl(t,i.value.from,i.value.to)){let{preparePlaceholder:n}=e.state.facet(ah),s=n?si.replace({widget:new fh(n(e.state,i.value))}):ch;t=t.update({add:[s.range(i.value.from,i.value.to)]})}else i.is(Ll)&&(t=t.update({filter:(t,e)=>i.value.from!=t||i.value.to!=e,filterFrom:i.value.from,filterTo:i.value.to}));if(e.selection){let i=!1,{head:n}=e.selection.main;t.between(n,n,((t,e)=>{t<n&&e>n&&(i=!0)})),i&&(t=t.update({filterFrom:n,filterTo:n,filter:(t,e)=>e<=n||t>=n}))}return t},provide:t=>Gs.decorations.from(t),toJSON(t,e){let i=[];return t.between(0,e.doc.length,((t,e)=>{i.push(t,e)})),i},fromJSON(t){if(!Array.isArray(t)||t.length%2)throw new RangeError("Invalid JSON for fold state");let e=[];for(let i=0;i<t.length;){let n=t[i++],s=t[i++];if("number"!=typeof n||"number"!=typeof s)throw new RangeError("Invalid JSON for fold state");e.push(ch.range(n,s))}return si.set(e,!0)}});function Hl(t,e,i){var n;let s=null;return null===(n=t.field(Ul,!1))||void 0===n||n.between(e,i,((t,e)=>{(!s||s.from>t)&&(s={from:t,to:e})})),s}function Fl(t,e,i){let n=!1;return t.between(e,e,((t,s)=>{t==e&&s==i&&(n=!0)})),n}function Jl(t,e){return t.field(Ul,!1)?e:e.concat(dt.appendConfig.of(lh()))}const Kl=t=>{for(let e of Nl(t)){let i=zl(t.state,e.from,e.to);if(i)return t.dispatch({effects:Jl(t.state,[Gl.of(i),eh(t,i)])}),!0}return!1},th=t=>{if(!t.state.field(Ul,!1))return!1;let e=[];for(let i of Nl(t)){let n=Hl(t.state,i.from,i.to);n&&e.push(Ll.of(n),eh(t,n,!1))}return e.length&&t.dispatch({effects:e}),e.length>0};function eh(t,e,i=!0){let n=t.state.doc.lineAt(e.from).number,s=t.state.doc.lineAt(e.to).number;return Gs.announce.of(`${t.state.phrase(i?"Folded lines":"Unfolded lines")} ${n} ${t.state.phrase("to")} ${s}.`)}const ih=t=>{let{state:e}=t,i=[];for(let n=0;n<e.doc.length;){let s=t.lineBlockAt(n),r=zl(e,s.from,s.to);r&&i.push(Gl.of(r)),n=(r?t.lineBlockAt(r.to):s).to+1}return i.length&&t.dispatch({effects:Jl(t.state,i)}),!!i.length},nh=t=>{let e=t.state.field(Ul,!1);if(!e||!e.size)return!1;let i=[];return e.between(0,t.state.doc.length,((t,e)=>{i.push(Ll.of({from:t,to:e}))})),t.dispatch({effects:i}),!0};function sh(t,e){for(let i=e;;){let n=zl(t.state,i.from,i.to);if(n&&n.to>e.from)return n;if(!i.from)return null;i=t.lineBlockAt(i.from-1)}}const rh=[{key:"Ctrl-Shift-[",mac:"Cmd-Alt-[",run:Kl},{key:"Ctrl-Shift-]",mac:"Cmd-Alt-]",run:th},{key:"Ctrl-Alt-[",run:ih},{key:"Ctrl-Alt-]",run:nh}],oh={placeholderDOM:null,preparePlaceholder:null,placeholderText:"…"},ah=j.define({combine:t=>$t(t,oh)});function lh(t){let e=[Ul,Oh];return t&&e.push(ah.of(t)),e}function hh(t,e){let{state:i}=t,n=i.facet(ah),s=e=>{let i=t.lineBlockAt(t.posAtDOM(e.target)),n=Hl(t.state,i.from,i.to);n&&t.dispatch({effects:Ll.of(n)}),e.preventDefault()};if(n.placeholderDOM)return n.placeholderDOM(t,s,e);let r=document.createElement("span");return r.textContent=n.placeholderText,r.setAttribute("aria-label",i.phrase("folded code")),r.title=i.phrase("unfold"),r.className="cm-foldPlaceholder",r.onclick=s,r}const ch=si.replace({widget:new class extends ii{toDOM(t){return hh(t,null)}}});class fh extends ii{constructor(t){super(),this.value=t}eq(t){return this.value==t.value}toDOM(t){return hh(t,this.value)}}const uh={openText:"⌄",closedText:"›",markerDOM:null,domEventHandlers:{},foldingChanged:()=>!1};class dh extends bo{constructor(t,e){super(),this.config=t,this.open=e}eq(t){return this.config==t.config&&this.open==t.open}toDOM(t){if(this.config.markerDOM)return this.config.markerDOM(this.open);let e=document.createElement("span");return e.textContent=this.open?this.config.openText:this.config.closedText,e.title=t.state.phrase(this.open?"Fold line":"Unfold line"),e}}function ph(t={}){let e=Object.assign(Object.assign({},uh),t),i=new dh(e,!0),n=new dh(e,!1),s=Ni.fromClass(class{constructor(t){this.from=t.viewport.from,this.markers=this.buildMarkers(t)}update(t){(t.docChanged||t.viewportChanged||t.startState.facet(bl)!=t.state.facet(bl)||t.startState.field(Ul,!1)!=t.state.field(Ul,!1)||cl(t.startState)!=cl(t.state)||e.foldingChanged(t))&&(this.markers=this.buildMarkers(t.view))}buildMarkers(t){let e=new Rt;for(let s of t.viewportLineBlocks){let r=Hl(t.state,s.from,s.to)?n:zl(t.state,s.from,s.to)?i:null;r&&e.add(s.from,s.from,r)}return e.finish()}}),{domEventHandlers:r}=e;return[s,ko({class:"cm-foldGutter",markers(t){var e;return(null===(e=t.plugin(s))||void 0===e?void 0:e.markers)||At.empty},initialSpacer:()=>new dh(e,!1),domEventHandlers:Object.assign(Object.assign({},r),{click:(t,e,i)=>{if(r.click&&r.click(t,e,i))return!0;let n=Hl(t.state,e.from,e.to);if(n)return t.dispatch({effects:Ll.of(n)}),!0;let s=zl(t.state,e.from,e.to);return!!s&&(t.dispatch({effects:Gl.of(s)}),!0)}})}),lh()]}const Oh=Gs.baseTheme({".cm-foldPlaceholder":{backgroundColor:"#eee",border:"1px solid #ddd",color:"#888",borderRadius:".2em",margin:"0 1px",padding:"0 1px",cursor:"pointer"},".cm-foldGutter span":{padding:"0 1px",cursor:"pointer"}});class gh{constructor(t,e){let i;function n(t){let e=Ut.newName();return(i||(i=Object.create(null)))["."+e]=t,e}this.specs=t;const s="string"==typeof e.all?e.all:e.all?n(e.all):void 0,r=e.scope;this.scope=r instanceof al?t=>t.prop(sl)==r.data:r?t=>t==r:void 0,this.style=Wa(t.map((t=>({tag:t.tag,class:t.class||n(Object.assign({},t,{tag:null}))}))),{all:s}).style,this.module=i?new Ut(i):null,this.themeType=e.themeType}static define(t,e){return new gh(t,e||{})}}const mh=j.define(),wh=j.define({combine:t=>t.length?[t[0]]:null});function vh(t){let e=t.facet(mh);return e.length?e:t.facet(wh)}function bh(t,e){let i,n=[Sh];return t instanceof gh&&(t.module&&n.push(Gs.styleModule.of(t.module)),i=t.themeType),(null==e?void 0:e.fallback)?n.push(wh.of(t)):i?n.push(mh.computeN([Gs.darkTheme],(e=>e.facet(Gs.darkTheme)==("dark"==i)?[t]:[]))):n.push(mh.of(t)),n}class yh{constructor(t){this.markCache=Object.create(null),this.tree=cl(t.state),this.decorations=this.buildDeco(t,vh(t.state)),this.decoratedTo=t.viewport.to}update(t){let e=cl(t.state),i=vh(t.state),n=i!=vh(t.startState),{viewport:s}=t.view,r=t.changes.mapPos(this.decoratedTo,1);e.length<s.to&&!n&&e.type==this.tree.type&&r>=s.to?(this.decorations=this.decorations.map(t.changes),this.decoratedTo=r):(e!=this.tree||t.viewportChanged||n)&&(this.tree=e,this.decorations=this.buildDeco(t.view,i),this.decoratedTo=s.to)}buildDeco(t,e){if(!e||!this.tree.length)return si.none;let i=new Rt;for(let{from:n,to:s}of t.visibleRanges)Ma(this.tree,e,((t,e,n)=>{i.add(t,e,this.markCache[n]||(this.markCache[n]=si.mark({class:n})))}),n,s);return i.finish()}}const Sh=H.high(Ni.fromClass(yh,{decorations:t=>t.decorations})),xh=gh.define([{tag:tl.meta,color:"#404740"},{tag:tl.link,textDecoration:"underline"},{tag:tl.heading,textDecoration:"underline",fontWeight:"bold"},{tag:tl.emphasis,fontStyle:"italic"},{tag:tl.strong,fontWeight:"bold"},{tag:tl.strikethrough,textDecoration:"line-through"},{tag:tl.keyword,color:"#708"},{tag:[tl.atom,tl.bool,tl.url,tl.contentSeparator,tl.labelName],color:"#219"},{tag:[tl.literal,tl.inserted],color:"#164"},{tag:[tl.string,tl.deleted],color:"#a11"},{tag:[tl.regexp,tl.escape,tl.special(tl.string)],color:"#e40"},{tag:tl.definition(tl.variableName),color:"#00f"},{tag:tl.local(tl.variableName),color:"#30a"},{tag:[tl.typeName,tl.namespace],color:"#085"},{tag:tl.className,color:"#167"},{tag:[tl.special(tl.variableName),tl.macroName],color:"#256"},{tag:tl.definition(tl.propertyName),color:"#00c"},{tag:tl.comment,color:"#940"},{tag:tl.invalid,color:"#f00"}]),kh=Gs.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),Qh=1e4,$h="()[]{}",Ph=j.define({combine:t=>$t(t,{afterCursor:!0,brackets:$h,maxScanDistance:Qh,renderMatch:Th})}),Zh=si.mark({class:"cm-matchingBracket"}),Ch=si.mark({class:"cm-nonmatchingBracket"});function Th(t){let e=[],i=t.matched?Zh:Ch;return e.push(i.range(t.start.from,t.start.to)),t.end&&e.push(i.range(t.end.from,t.end.to)),e}const Ah=z.define({create:()=>si.none,update(t,e){if(!e.docChanged&&!e.selection)return t;let i=[],n=e.state.facet(Ph);for(let t of e.state.selection.ranges){if(!t.empty)continue;let s=jh(e.state,t.head,-1,n)||t.head>0&&jh(e.state,t.head-1,1,n)||n.afterCursor&&(jh(e.state,t.head,1,n)||t.head<e.state.doc.length&&jh(e.state,t.head+1,-1,n));s&&(i=i.concat(n.renderMatch(s,e.state)))}return si.set(i,!0)},provide:t=>Gs.decorations.from(t)}),Rh=[Ah,kh];function Xh(t={}){return[Ph.of(t),Rh]}const Yh=new Jo;function Wh(t,e,i){let n=t.prop(e<0?Jo.openedBy:Jo.closedBy);if(n)return n;if(1==t.name.length){let n=i.indexOf(t.name);if(n>-1&&n%2==(e<0?1:0))return[i[n+e]]}return null}function Mh(t){let e=t.type.prop(Yh);return e?e(t.node):t}function jh(t,e,i,n={}){let s=n.maxScanDistance||Qh,r=n.brackets||$h,o=cl(t),a=o.resolveInner(e,i);for(let n=a;n;n=n.parent){let s=Wh(n.type,i,r);if(s&&n.from<n.to){let o=Mh(n);if(o&&(i>0?e>=o.from&&e<o.to:e>o.from&&e<=o.to))return Dh(t,e,i,n,o,s,r)}}return function(t,e,i,n,s,r,o){let a=i<0?t.sliceDoc(e-1,e):t.sliceDoc(e,e+1),l=o.indexOf(a);if(l<0||l%2==0!=i>0)return null;let h={from:i<0?e-1:e,to:i>0?e+1:e},c=t.doc.iterRange(e,i>0?t.doc.length:0),f=0;for(let t=0;!c.next().done&&t<=r;){let r=c.value;i<0&&(t+=r.length);let a=e+t*i;for(let t=i>0?0:r.length-1,e=i>0?r.length:-1;t!=e;t+=i){let e=o.indexOf(r[t]);if(!(e<0||n.resolveInner(a+t,1).type!=s))if(e%2==0==i>0)f++;else{if(1==f)return{start:h,end:{from:a+t,to:a+t+1},matched:e>>1==l>>1};f--}}i>0&&(t+=r.length)}return c.done?{start:h,matched:!1}:null}(t,e,i,o,a.type,s,r)}function Dh(t,e,i,n,s,r,o){let a=n.parent,l={from:s.from,to:s.to},h=0,c=null==a?void 0:a.cursor();if(c&&(i<0?c.childBefore(n.from):c.childAfter(n.to)))do{if(i<0?c.to<=n.from:c.from>=n.to){if(0==h&&r.indexOf(c.type.name)>-1&&c.from<c.to){let t=Mh(c);return{start:l,end:t?{from:t.from,to:t.to}:void 0,matched:!0}}if(Wh(c.type,i,o))h++;else if(Wh(c.type,-i,o)){if(0==h){let t=Mh(c);return{start:l,end:t&&t.from<t.to?{from:t.from,to:t.to}:void 0,matched:!1}}h--}}}while(i<0?c.prevSibling():c.nextSibling());return{start:l,matched:!1}}function Eh(t,e,i,n=0,s=0){null==e&&-1==(e=t.search(/[^\s\u00a0]/))&&(e=t.length);let r=s;for(let s=n;s<e;s++)9==t.charCodeAt(s)?r+=i-r%i:r++;return r}class qh{constructor(t,e,i,n){this.string=t,this.tabSize=e,this.indentUnit=i,this.overrideIndent=n,this.pos=0,this.start=0,this.lastColumnPos=0,this.lastColumnValue=0}eol(){return this.pos>=this.string.length}sol(){return 0==this.pos}peek(){return this.string.charAt(this.pos)||void 0}next(){if(this.pos<this.string.length)return this.string.charAt(this.pos++)}eat(t){let e,i=this.string.charAt(this.pos);if(e="string"==typeof t?i==t:i&&(t instanceof RegExp?t.test(i):t(i)),e)return++this.pos,i}eatWhile(t){let e=this.pos;for(;this.eat(t););return this.pos>e}eatSpace(){let t=this.pos;for(;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>t}skipToEnd(){this.pos=this.string.length}skipTo(t){let e=this.string.indexOf(t,this.pos);if(e>-1)return this.pos=e,!0}backUp(t){this.pos-=t}column(){return this.lastColumnPos<this.start&&(this.lastColumnValue=Eh(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue),this.lastColumnPos=this.start),this.lastColumnValue}indentation(){var t;return null!==(t=this.overrideIndent)&&void 0!==t?t:Eh(this.string,null,this.tabSize)}match(t,e,i){if("string"==typeof t){let n=t=>i?t.toLowerCase():t;return n(this.string.substr(this.pos,t.length))==n(t)?(!1!==e&&(this.pos+=t.length),!0):null}{let i=this.string.slice(this.pos).match(t);return i&&i.index>0?null:(i&&!1!==e&&(this.pos+=i[0].length),i)}}current(){return this.string.slice(this.start,this.pos)}}function _h(t){if("object"!=typeof t)return t;let e={};for(let i in t){let n=t[i];e[i]=n instanceof Array?n.slice():n}return e}const Vh=new WeakMap;class Ih extends al{constructor(t){let e,i=rl(t.languageData),n={name:(s=t).name||"",token:s.token,blankLine:s.blankLine||(()=>{}),startState:s.startState||(()=>!0),copyState:s.copyState||_h,indent:s.indent||(()=>null),languageData:s.languageData||{},tokenTable:s.tokenTable||Nh};var s;super(i,new class extends $a{createParse(t,i,n){return new Gh(e,t,i,n)}},[xl.of(((t,e)=>this.getIndent(t,e)))],t.name),this.topNode=function(t){let e=ea.define({id:Uh.length,name:"Document",props:[sl.add((()=>t))],top:!0});return Uh.push(e),e}(i),e=this,this.streamParser=n,this.stateAfter=new Jo({perNode:!0}),this.tokenTable=t.tokenTable?new tc(n.tokenTable):ec}static define(t){return new Ih(t)}getIndent(t,e){let i,n=cl(t.state),s=n.resolve(e);for(;s&&s.type!=this.topNode;)s=s.parent;if(!s)return null;let{overrideIndentation:r}=t.options;r&&(i=Vh.get(t.state),null!=i&&i<e-1e4&&(i=void 0));let o,a,l=zh(this,n,0,s.from,null!=i?i:e);if(l?(a=l.state,o=l.pos+1):(a=this.streamParser.startState(t.unit),o=0),e-o>1e4)return null;for(;o<e;){let i=t.state.doc.lineAt(o),n=Math.min(e,i.to);if(i.length){let e=r?r(i.from):-1,s=new qh(i.text,t.state.tabSize,t.unit,e<0?void 0:e);for(;s.pos<n-i.from;)Lh(this.streamParser.token,s,a)}else this.streamParser.blankLine(a,t.unit);if(n==e)break;o=i.to+1}let h=t.lineAt(e);return r&&null==i&&Vh.set(t.state,h.from),this.streamParser.indent(a,/^\s*(.*)/.exec(h.text)[1],t)}get allowsNesting(){return!1}}function zh(t,e,i,n,s){let r=i>=n&&i+e.length<=s&&e.prop(t.stateAfter);if(r)return{state:t.streamParser.copyState(r),pos:i+e.length};for(let r=e.children.length-1;r>=0;r--){let o=e.children[r],a=i+e.positions[r],l=o instanceof oa&&a<s&&zh(t,o,a,n,s);if(l)return l}return null}function Bh(t,e,i,n,s){if(s&&i<=0&&n>=e.length)return e;s||e.type!=t.topNode||(s=!0);for(let r=e.children.length-1;r>=0;r--){let o,a=e.positions[r],l=e.children[r];if(a<n&&l instanceof oa){if(!(o=Bh(t,l,i-a,n-a,s)))break;return s?new oa(e.type,e.children.slice(0,r).concat(o),e.positions.slice(0,r+1),a+o.length):o}}return null}let Gh=class{constructor(t,e,i,n){this.lang=t,this.input=e,this.fragments=i,this.ranges=n,this.stoppedAt=null,this.chunks=[],this.chunkPos=[],this.chunk=[],this.chunkReused=void 0,this.rangeIndex=0,this.to=n[n.length-1].to;let s=pl.get(),r=n[0].from,{state:o,tree:a}=function(t,e,i,n){for(let n of e){let e,s=n.from+(n.openStart?25:0),r=n.to-(n.openEnd?25:0),o=s<=i&&r>i&&zh(t,n.tree,0-n.offset,i,r);if(o&&(e=Bh(t,n.tree,i+n.offset,o.pos+n.offset,!1)))return{state:o.state,tree:e}}return{state:t.streamParser.startState(n?Ql(n):4),tree:oa.empty}}(t,i,r,null==s?void 0:s.state);this.state=o,this.parsedPos=this.chunkStart=r+a.length;for(let t=0;t<a.children.length;t++)this.chunks.push(a.children[t]),this.chunkPos.push(a.positions[t]);s&&this.parsedPos<s.viewport.from-1e5&&(this.state=this.lang.streamParser.startState(Ql(s.state)),s.skipUntilInView(this.parsedPos,s.viewport.from),this.parsedPos=s.viewport.from),this.moveRangeIndex()}advance(){let t=pl.get(),e=null==this.stoppedAt?this.to:Math.min(this.to,this.stoppedAt),i=Math.min(e,this.chunkStart+2048);for(t&&(i=Math.min(i,t.viewport.to));this.parsedPos<i;)this.parseLine(t);return this.chunkStart<this.parsedPos&&this.finishChunk(),this.parsedPos>=e?this.finish():t&&this.parsedPos>=t.viewport.to?(t.skipUntilInView(this.parsedPos,e),this.finish()):null}stopAt(t){this.stoppedAt=t}lineAfter(t){let e=this.input.chunk(t);if(this.input.lineChunks)"\n"==e&&(e="");else{let t=e.indexOf("\n");t>-1&&(e=e.slice(0,t))}return t+e.length<=this.to?e:e.slice(0,this.to-t)}nextLine(){let t=this.parsedPos,e=this.lineAfter(t),i=t+e.length;for(let t=this.rangeIndex;;){let n=this.ranges[t].to;if(n>=i)break;if(e=e.slice(0,n-(i-e.length)),t++,t==this.ranges.length)break;let s=this.ranges[t].from,r=this.lineAfter(s);e+=r,i=s+r.length}return{line:e,end:i}}skipGapsTo(t,e,i){for(;;){let n=this.ranges[this.rangeIndex].to,s=t+e;if(i>0?n>s:n>=s)break;e+=this.ranges[++this.rangeIndex].from-n}return e}moveRangeIndex(){for(;this.ranges[this.rangeIndex].to<this.parsedPos;)this.rangeIndex++}emitToken(t,e,i,n,s){if(this.ranges.length>1){e+=s=this.skipGapsTo(e,s,1);let t=this.chunk.length;i+=s=this.skipGapsTo(i,s,-1),n+=this.chunk.length-t}return this.chunk.push(t,e,i,n),s}parseLine(t){let{line:e,end:i}=this.nextLine(),n=0,{streamParser:s}=this.lang,r=new qh(e,t?t.state.tabSize:4,t?Ql(t.state):2);if(r.eol())s.blankLine(this.state,r.indentUnit);else for(;!r.eol();){let t=Lh(s.token,r,this.state);if(t&&(n=this.emitToken(this.lang.tokenTable.resolve(t),this.parsedPos+r.start,this.parsedPos+r.pos,4,n)),r.start>1e4)break}this.parsedPos=i,this.moveRangeIndex(),this.parsedPos<this.to&&this.parsedPos++}finishChunk(){let t=oa.build({buffer:this.chunk,start:this.chunkStart,length:this.parsedPos-this.chunkStart,nodeSet:Hh,topID:0,maxBufferLength:2048,reused:this.chunkReused});t=new oa(t.type,t.children,t.positions,t.length,[[this.lang.stateAfter,this.lang.streamParser.copyState(this.state)]]),this.chunks.push(t),this.chunkPos.push(this.chunkStart-this.ranges[0].from),this.chunk=[],this.chunkReused=void 0,this.chunkStart=this.parsedPos}finish(){return new oa(this.lang.topNode,this.chunks,this.chunkPos,this.parsedPos-this.ranges[0].from).balance()}};function Lh(t,e,i){e.start=e.pos;for(let n=0;n<10;n++){let n=t(e,i);if(e.pos>e.start)return n}throw new Error("Stream parser failed to advance stream.")}const Nh=Object.create(null),Uh=[ea.none],Hh=new ia(Uh),Fh=[],Jh=Object.create(null),Kh=Object.create(null);for(let[t,e]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])Kh[t]=nc(Nh,e);class tc{constructor(t){this.extra=t,this.table=Object.assign(Object.create(null),Kh)}resolve(t){return t?this.table[t]||(this.table[t]=nc(this.extra,t)):0}}const ec=new tc(Nh);function ic(t,e){Fh.indexOf(t)>-1||(Fh.push(t),console.warn(e))}function nc(t,e){let i=[];for(let n of e.split(" ")){let e=[];for(let i of n.split(".")){let n=t[i]||tl[i];n?"function"==typeof n?e.length?e=e.map(n):ic(i,`Modifier ${i} used at start of tag`):e.length?ic(i,`Tag ${i} used as modifier`):e=Array.isArray(n)?n:[n]:ic(i,`Unknown highlighting tag ${i}`)}for(let t of e)i.push(t)}if(!i.length)return 0;let n=e.replace(/ /g,"_"),s=n+" "+i.map((t=>t.id)),r=Jh[s];if(r)return r.id;let o=Jh[s]=ea.define({id:Uh.length,name:n,props:[Ra({[n]:i})]});return Uh.push(o),o.id}function sc(t){return t.length<=4096&&/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac\ufb50-\ufdff]/.test(t)}function rc(t){for(let e=t.iter();!e.next().done;)if(sc(e.value))return!0;return!1}const oc=j.define({combine:t=>t.some((t=>t))});const ac=Ni.fromClass(class{constructor(t){this.always=t.state.facet(oc)||t.textDirection!=di.LTR||t.state.facet(Gs.perLineTextDirection),this.hasRTL=!this.always&&rc(t.state.doc),this.tree=cl(t.state),this.decorations=this.always||this.hasRTL?lc(t,this.tree,this.always):si.none}update(t){let e=t.state.facet(oc)||t.view.textDirection!=di.LTR||t.state.facet(Gs.perLineTextDirection);if(e||this.hasRTL||!function(t){let e=!1;return t.iterChanges(((t,i,n,s,r)=>{!e&&rc(r)&&(e=!0)})),e}(t.changes)||(this.hasRTL=!0),!e&&!this.hasRTL)return;let i=cl(t.state);(e!=this.always||i!=this.tree||t.docChanged||t.viewportChanged)&&(this.tree=i,this.always=e,this.decorations=lc(t.view,i,e))}},{provide:t=>{function e(e){var i,n;return null!==(n=null===(i=e.plugin(t))||void 0===i?void 0:i.decorations)&&void 0!==n?n:si.none}return[Gs.outerDecorations.of(e),H.lowest(Gs.bidiIsolatedRanges.of(e))]}});function lc(t,e,i){let n=new Rt,s=t.visibleRanges;i||(s=function(t,e){let i=e.iter(),n=0,s=[],r=null;for(let{from:e,to:o}of t)for(e!=n&&(n<e&&i.next(e-n),n=e);;){let t=n,e=n+i.value.length;if(!i.lineBreak&&sc(i.value)&&(r&&r.to>t-10?r.to=Math.min(o,e):s.push(r={from:t,to:Math.min(o,e)})),n>=o)break;n=e,i.next()}return s}(s,t.state.doc));for(let{from:t,to:i}of s)e.iterate({enter:t=>{let e=t.type.prop(Jo.isolate);e&&n.add(t.from,t.to,hc[e])},from:t,to:i});return n.finish()}const hc={rtl:si.mark({class:"cm-iso",inclusive:!0,attributes:{dir:"rtl"},bidiIsolate:di.RTL}),ltr:si.mark({class:"cm-iso",inclusive:!0,attributes:{dir:"ltr"},bidiIsolate:di.LTR}),auto:si.mark({class:"cm-iso",inclusive:!0,attributes:{dir:"auto"},bidiIsolate:null})};var cc=Object.freeze({__proto__:null,DocInput:ul,HighlightStyle:gh,IndentContext:Zl,LRLanguage:hl,Language:al,LanguageDescription:Sl,LanguageSupport:yl,ParseContext:pl,StreamLanguage:Ih,StringStream:qh,TreeIndentContext:Xl,bidiIsolates:function(t={}){let e=[ac];return t.alwaysIsolate&&e.push(oc.of(!0)),e},bracketMatching:Xh,bracketMatchingHandle:Yh,codeFolding:lh,continuedIndent:Dl,defaultHighlightStyle:xh,defineLanguageFacet:rl,delimitedIndent:Wl,ensureSyntaxTree:fl,flatIndent:jl,foldAll:ih,foldCode:Kl,foldEffect:Gl,foldGutter:ph,foldInside:Vl,foldKeymap:rh,foldNodeProp:_l,foldService:ql,foldState:Ul,foldable:zl,foldedRanges:function(t){return t.field(Ul,!1)||At.empty},forceParsing:function(t,e=t.viewport.to,i=100){let n=fl(t.state,e,i);return n!=cl(t.state)&&t.dispatch({}),!!n},getIndentUnit:Ql,getIndentation:Pl,highlightingFor:function(t,e,i){let n=vh(t),s=null;if(n)for(let t of n)if(!t.scope||i&&t.scope(i)){let i=t.style(e);i&&(s=s?s+" "+i:i)}return s},indentNodeProp:Cl,indentOnInput:El,indentRange:function(t,e,i){let n=Object.create(null),s=new Zl(t,{overrideIndentation:t=>{var e;return null!==(e=n[t])&&void 0!==e?e:-1}}),r=[];for(let o=e;o<=i;){let e=t.doc.lineAt(o);o=e.to+1;let i=Pl(s,e.from);if(null==i)continue;/\S/.test(e.text)||(i=0);let a=/^\s*/.exec(e.text)[0],l=$l(t,i);a!=l&&(n[e.from]=i,r.push({from:e.from,to:e.from+a.length,insert:l}))}return t.changes(r)},indentService:xl,indentString:$l,indentUnit:kl,language:bl,languageDataProp:sl,matchBrackets:jh,sublanguageProp:ol,syntaxHighlighting:bh,syntaxParserRunning:function(t){var e;return(null===(e=t.plugin(vl))||void 0===e?void 0:e.isWorking())||!1},syntaxTree:cl,syntaxTreeAvailable:function(t,e=t.doc.length){var i;return(null===(i=t.field(al.state,!1))||void 0===i?void 0:i.context.isDone(e))||!1},toggleFold:t=>{let e=[];for(let i of Nl(t)){let n=Hl(t.state,i.from,i.to);if(n)e.push(Ll.of(n),eh(t,n,!1));else{let n=sh(t,i);n&&e.push(Gl.of(n),eh(t,n))}}return e.length>0&&t.dispatch({effects:Jl(t.state,e)}),!!e.length},unfoldAll:nh,unfoldCode:th,unfoldEffect:Ll});function fc(t,e){return({state:i,dispatch:n})=>{if(i.readOnly)return!1;let s=t(e,i);return!!s&&(n(i.update(s)),!0)}}const uc=fc(wc,0),dc=fc(mc,0),pc=fc(((t,e)=>mc(t,e,function(t){let e=[];for(let i of t.selection.ranges){let n=t.doc.lineAt(i.from),s=i.to<=n.to?n:t.doc.lineAt(i.to),r=e.length-1;r>=0&&e[r].to>n.from?e[r].to=s.to:e.push({from:n.from+/^\s*/.exec(n.text)[0].length,to:s.to})}return e}(e))),0);function Oc(t,e){let i=t.languageDataAt("commentTokens",e);return i.length?i[0]:{}}const gc=50;function mc(t,e,i=e.selection.ranges){let n=i.map((t=>Oc(e,t.from).block));if(!n.every((t=>t)))return null;let s=i.map(((t,i)=>function(t,{open:e,close:i},n,s){let r,o,a=t.sliceDoc(n-gc,n),l=t.sliceDoc(s,s+gc),h=/\s*$/.exec(a)[0].length,c=/^\s*/.exec(l)[0].length,f=a.length-h;if(a.slice(f-e.length,f)==e&&l.slice(c,c+i.length)==i)return{open:{pos:n-h,margin:h&&1},close:{pos:s+c,margin:c&&1}};s-n<=2*gc?r=o=t.sliceDoc(n,s):(r=t.sliceDoc(n,n+gc),o=t.sliceDoc(s-gc,s));let u=/^\s*/.exec(r)[0].length,d=/\s*$/.exec(o)[0].length,p=o.length-d-i.length;return r.slice(u,u+e.length)==e&&o.slice(p,p+i.length)==i?{open:{pos:n+u+e.length,margin:/\s/.test(r.charAt(u+e.length))?1:0},close:{pos:s-d-i.length,margin:/\s/.test(o.charAt(p-1))?1:0}}:null}(e,n[i],t.from,t.to)));if(2!=t&&!s.every((t=>t)))return{changes:e.changes(i.map(((t,e)=>s[e]?[]:[{from:t.from,insert:n[e].open+" "},{from:t.to,insert:" "+n[e].close}])))};if(1!=t&&s.some((t=>t))){let t=[];for(let e,i=0;i<s.length;i++)if(e=s[i]){let s=n[i],{open:r,close:o}=e;t.push({from:r.pos-s.open.length,to:r.pos+r.margin},{from:o.pos-o.margin,to:o.pos+s.close.length})}return{changes:t}}return null}function wc(t,e,i=e.selection.ranges){let n=[],s=-1;for(let{from:t,to:r}of i){let i=n.length,o=1e9,a=Oc(e,t).line;if(a){for(let i=t;i<=r;){let l=e.doc.lineAt(i);if(l.from>s&&(t==r||r>l.from)){s=l.from;let t=/^\s*/.exec(l.text)[0].length,e=t==l.length,i=l.text.slice(t,t+a.length)==a?t:-1;t<l.text.length&&t<o&&(o=t),n.push({line:l,comment:i,token:a,indent:t,empty:e,single:!1})}i=l.to+1}if(o<1e9)for(let t=i;t<n.length;t++)n[t].indent<n[t].line.text.length&&(n[t].indent=o);n.length==i+1&&(n[i].single=!0)}}if(2!=t&&n.some((t=>t.comment<0&&(!t.empty||t.single)))){let t=[];for(let{line:e,token:i,indent:s,empty:r,single:o}of n)!o&&r||t.push({from:e.from+s,insert:i+" "});let i=e.changes(t);return{changes:i,selection:e.selection.map(i,1)}}if(1!=t&&n.some((t=>t.comment>=0))){let t=[];for(let{line:e,comment:i,token:s}of n)if(i>=0){let n=e.from+i,r=n+s.length;" "==e.text[r-e.from]&&r++,t.push({from:n,to:r})}return{changes:t}}return null}const vc=ct.define(),bc=ct.define(),yc=j.define(),Sc=j.define({combine:t=>$t(t,{minDepth:100,newGroupDelay:500,joinToEvent:(t,e)=>e},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(t,e)=>(i,n)=>t(i,n)||e(i,n)})}),xc=z.define({create:()=>qc.empty,update(t,e){let i=e.state.facet(Sc),n=e.annotation(vc);if(n){let s=Tc.fromTransaction(e,n.selection),r=n.side,o=0==r?t.undone:t.done;return o=s?Ac(o,o.length,i.minDepth,s):Wc(o,e.startState.selection),new qc(0==r?n.rest:o,0==r?o:n.rest)}let s=e.annotation(bc);if("full"!=s&&"before"!=s||(t=t.isolate()),!1===e.annotation(pt.addToHistory))return e.changes.empty?t:t.addMapping(e.changes.desc);let r=Tc.fromTransaction(e),o=e.annotation(pt.time),a=e.annotation(pt.userEvent);return r?t=t.addChanges(r,o,a,i,e):e.selection&&(t=t.addSelection(e.startState.selection,o,a,i.newGroupDelay)),"full"!=s&&"after"!=s||(t=t.isolate()),t},toJSON:t=>({done:t.done.map((t=>t.toJSON())),undone:t.undone.map((t=>t.toJSON()))}),fromJSON:t=>new qc(t.done.map(Tc.fromJSON),t.undone.map(Tc.fromJSON))});function kc(t={}){return[xc,Sc.of(t),Gs.domEventHandlers({beforeinput(t,e){let i="historyUndo"==t.inputType?$c:"historyRedo"==t.inputType?Pc:null;return!!i&&(t.preventDefault(),i(e))}})]}function Qc(t,e){return function({state:i,dispatch:n}){if(!e&&i.readOnly)return!1;let s=i.field(xc,!1);if(!s)return!1;let r=s.pop(t,i,e);return!!r&&(n(r),!0)}}const $c=Qc(0,!1),Pc=Qc(1,!1),Zc=Qc(0,!0),Cc=Qc(1,!0);class Tc{constructor(t,e,i,n,s){this.changes=t,this.effects=e,this.mapped=i,this.startSelection=n,this.selectionsAfter=s}setSelAfter(t){return new Tc(this.changes,this.effects,this.mapped,this.startSelection,t)}toJSON(){var t,e,i;return{changes:null===(t=this.changes)||void 0===t?void 0:t.toJSON(),mapped:null===(e=this.mapped)||void 0===e?void 0:e.toJSON(),startSelection:null===(i=this.startSelection)||void 0===i?void 0:i.toJSON(),selectionsAfter:this.selectionsAfter.map((t=>t.toJSON()))}}static fromJSON(t){return new Tc(t.changes&&$.fromJSON(t.changes),[],t.mapped&&Q.fromJSON(t.mapped),t.startSelection&&Y.fromJSON(t.startSelection),t.selectionsAfter.map(Y.fromJSON))}static fromTransaction(t,e){let i=Xc;for(let e of t.startState.facet(yc)){let n=e(t);n.length&&(i=i.concat(n))}return!i.length&&t.changes.empty?null:new Tc(t.changes.invert(t.startState.doc),i,void 0,e||t.startState.selection,Xc)}static selection(t){return new Tc(void 0,Xc,void 0,void 0,t)}}function Ac(t,e,i,n){let s=e+1>i+20?e-i-1:0,r=t.slice(s,e);return r.push(n),r}function Rc(t,e){return t.length?e.length?t.concat(e):t:e}const Xc=[],Yc=200;function Wc(t,e){if(t.length){let i=t[t.length-1],n=i.selectionsAfter.slice(Math.max(0,i.selectionsAfter.length-Yc));return n.length&&n[n.length-1].eq(e)?t:(n.push(e),Ac(t,t.length-1,1e9,i.setSelAfter(n)))}return[Tc.selection([e])]}function Mc(t){let e=t[t.length-1],i=t.slice();return i[t.length-1]=e.setSelAfter(e.selectionsAfter.slice(0,e.selectionsAfter.length-1)),i}function jc(t,e){if(!t.length)return t;let i=t.length,n=Xc;for(;i;){let s=Dc(t[i-1],e,n);if(s.changes&&!s.changes.empty||s.effects.length){let e=t.slice(0,i);return e[i-1]=s,e}e=s.mapped,i--,n=s.selectionsAfter}return n.length?[Tc.selection(n)]:Xc}function Dc(t,e,i){let n=Rc(t.selectionsAfter.length?t.selectionsAfter.map((t=>t.map(e))):Xc,i);if(!t.changes)return Tc.selection(n);let s=t.changes.map(e),r=e.mapDesc(t.changes,!0),o=t.mapped?t.mapped.composeDesc(r):r;return new Tc(s,dt.mapEffects(t.effects,e),o,t.startSelection.map(r),n)}const Ec=/^(input\.type|delete)($|\.)/;class qc{constructor(t,e,i=0,n=void 0){this.done=t,this.undone=e,this.prevTime=i,this.prevUserEvent=n}isolate(){return this.prevTime?new qc(this.done,this.undone):this}addChanges(t,e,i,n,s){let r=this.done,o=r[r.length-1];return r=o&&o.changes&&!o.changes.empty&&t.changes&&(!i||Ec.test(i))&&(!o.selectionsAfter.length&&e-this.prevTime<n.newGroupDelay&&n.joinToEvent(s,function(t,e){let i=[],n=!1;return t.iterChangedRanges(((t,e)=>i.push(t,e))),e.iterChangedRanges(((t,e,s,r)=>{for(let t=0;t<i.length;){let e=i[t++],o=i[t++];r>=e&&s<=o&&(n=!0)}})),n}(o.changes,t.changes))||"input.type.compose"==i)?Ac(r,r.length-1,n.minDepth,new Tc(t.changes.compose(o.changes),Rc(t.effects,o.effects),o.mapped,o.startSelection,Xc)):Ac(r,r.length,n.minDepth,t),new qc(r,Xc,e,i)}addSelection(t,e,i,n){let s=this.done.length?this.done[this.done.length-1].selectionsAfter:Xc;return s.length>0&&e-this.prevTime<n&&i==this.prevUserEvent&&i&&/^select($|\.)/.test(i)&&(r=s[s.length-1],o=t,r.ranges.length==o.ranges.length&&0===r.ranges.filter(((t,e)=>t.empty!=o.ranges[e].empty)).length)?this:new qc(Wc(this.done,t),this.undone,e,i);var r,o}addMapping(t){return new qc(jc(this.done,t),jc(this.undone,t),this.prevTime,this.prevUserEvent)}pop(t,e,i){let n=0==t?this.done:this.undone;if(0==n.length)return null;let s=n[n.length-1],r=s.selectionsAfter[0]||e.selection;if(i&&s.selectionsAfter.length)return e.update({selection:s.selectionsAfter[s.selectionsAfter.length-1],annotations:vc.of({side:t,rest:Mc(n),selection:r}),userEvent:0==t?"select.undo":"select.redo",scrollIntoView:!0});if(s.changes){let i=1==n.length?Xc:n.slice(0,n.length-1);return s.mapped&&(i=jc(i,s.mapped)),e.update({changes:s.changes,selection:s.startSelection,effects:s.effects,annotations:vc.of({side:t,rest:i,selection:r}),filter:!1,userEvent:0==t?"undo":"redo",scrollIntoView:!0})}return null}}qc.empty=new qc(Xc,Xc);const _c=[{key:"Mod-z",run:$c,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:Pc,preventDefault:!0},{linux:"Ctrl-Shift-z",run:Pc,preventDefault:!0},{key:"Mod-u",run:Zc,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:Cc,preventDefault:!0}];function Vc(t,e){return Y.create(t.ranges.map(e),t.mainIndex)}function Ic(t,e){return t.update({selection:e,scrollIntoView:!0,userEvent:"select"})}function zc({state:t,dispatch:e},i){let n=Vc(t.selection,i);return!n.eq(t.selection,!0)&&(e(Ic(t,n)),!0)}function Bc(t,e){return Y.cursor(e?t.to:t.from)}function Gc(t,e){return zc(t,(i=>i.empty?t.moveByChar(i,e):Bc(i,e)))}function Lc(t){return t.textDirectionAt(t.state.selection.main.head)==di.LTR}const Nc=t=>Gc(t,!Lc(t)),Uc=t=>Gc(t,Lc(t));function Hc(t,e){return zc(t,(i=>i.empty?t.moveByGroup(i,e):Bc(i,e)))}function Fc(t,e,i){if(e.type.prop(i))return!0;let n=e.to-e.from;return n&&(n>2||/[^\s,.;:]/.test(t.sliceDoc(e.from,e.to)))||e.firstChild}function Jc(t,e,i){let n,s,r=cl(t).resolveInner(e.head),o=i?Jo.closedBy:Jo.openedBy;for(let n=e.head;;){let e=i?r.childAfter(n):r.childBefore(n);if(!e)break;Fc(t,e,o)?r=e:n=i?e.to:e.from}return s=r.type.prop(o)&&(n=i?jh(t,r.from,1):jh(t,r.to,-1))&&n.matched?i?n.end.to:n.end.from:i?r.to:r.from,Y.cursor(s,i?-1:1)}function Kc(t,e){return zc(t,(i=>{if(!i.empty)return Bc(i,e);let n=t.moveVertically(i,e);return n.head!=i.head?n:t.moveToLineBoundary(i,e)}))}const tf=t=>Kc(t,!1),ef=t=>Kc(t,!0);function nf(t){let e,i=t.scrollDOM.clientHeight<t.scrollDOM.scrollHeight-2,n=0,s=0;if(i){for(let e of t.state.facet(Gs.scrollMargins)){let i=e(t);(null==i?void 0:i.top)&&(n=Math.max(null==i?void 0:i.top,n)),(null==i?void 0:i.bottom)&&(s=Math.max(null==i?void 0:i.bottom,s))}e=t.scrollDOM.clientHeight-n-s}else e=(t.dom.ownerDocument.defaultView||window).innerHeight;return{marginTop:n,marginBottom:s,selfScroll:i,height:Math.max(t.defaultLineHeight,e-5)}}function sf(t,e){let i,n=nf(t),{state:s}=t,r=Vc(s.selection,(i=>i.empty?t.moveVertically(i,e,n.height):Bc(i,e)));if(r.eq(s.selection))return!1;if(n.selfScroll){let e=t.coordsAtPos(s.selection.main.head),o=t.scrollDOM.getBoundingClientRect(),a=o.top+n.marginTop,l=o.bottom-n.marginBottom;e&&e.top>a&&e.bottom<l&&(i=Gs.scrollIntoView(r.main.head,{y:"start",yMargin:e.top-a}))}return t.dispatch(Ic(s,r),{effects:i}),!0}const rf=t=>sf(t,!1),of=t=>sf(t,!0);function af(t,e,i){let n=t.lineBlockAt(e.head),s=t.moveToLineBoundary(e,i);if(s.head==e.head&&s.head!=(i?n.to:n.from)&&(s=t.moveToLineBoundary(e,i,!1)),!i&&s.head==n.from&&n.length){let i=/^\s*/.exec(t.state.sliceDoc(n.from,Math.min(n.from+100,n.to)))[0].length;i&&e.head!=n.from+i&&(s=Y.cursor(n.from+i))}return s}function lf(t,e){let i=Vc(t.state.selection,(t=>{let i=e(t);return Y.range(t.anchor,i.head,i.goalColumn,i.bidiLevel||void 0)}));return!i.eq(t.state.selection)&&(t.dispatch(Ic(t.state,i)),!0)}function hf(t,e){return lf(t,(i=>t.moveByChar(i,e)))}const cf=t=>hf(t,!Lc(t)),ff=t=>hf(t,Lc(t));function uf(t,e){return lf(t,(i=>t.moveByGroup(i,e)))}function df(t,e){return lf(t,(i=>t.moveVertically(i,e)))}const pf=t=>df(t,!1),Of=t=>df(t,!0);function gf(t,e){return lf(t,(i=>t.moveVertically(i,e,nf(t).height)))}const mf=t=>gf(t,!1),wf=t=>gf(t,!0),vf=({state:t,dispatch:e})=>(e(Ic(t,{anchor:0})),!0),bf=({state:t,dispatch:e})=>(e(Ic(t,{anchor:t.doc.length})),!0),yf=({state:t,dispatch:e})=>(e(Ic(t,{anchor:t.selection.main.anchor,head:0})),!0),Sf=({state:t,dispatch:e})=>(e(Ic(t,{anchor:t.selection.main.anchor,head:t.doc.length})),!0);function xf(t,e){if(t.state.readOnly)return!1;let i="delete.selection",{state:n}=t,s=n.changeByRange((n=>{let{from:s,to:r}=n;if(s==r){let o=e(n);o<s?(i="delete.backward",o=kf(t,o,!1)):o>s&&(i="delete.forward",o=kf(t,o,!0)),s=Math.min(s,o),r=Math.max(r,o)}else s=kf(t,s,!1),r=kf(t,r,!0);return s==r?{range:n}:{changes:{from:s,to:r},range:Y.cursor(s,s<n.head?-1:1)}}));return!s.changes.empty&&(t.dispatch(n.update(s,{scrollIntoView:!0,userEvent:i,effects:"delete.selection"==i?Gs.announce.of(n.phrase("Selection deleted")):void 0})),!0)}function kf(t,e,i){if(t instanceof Gs)for(let n of t.state.facet(Gs.atomicRanges).map((e=>e(t))))n.between(e,e,((t,n)=>{t<e&&n>e&&(e=i?n:t)}));return e}const Qf=(t,e)=>xf(t,(i=>{let n,s,r=i.from,{state:o}=t,a=o.doc.lineAt(r);if(!e&&r>a.from&&r<a.from+200&&!/[^ \t]/.test(n=a.text.slice(0,r-a.from))){if("\t"==n[n.length-1])return r-1;let t=It(n,o.tabSize)%Ql(o)||Ql(o);for(let e=0;e<t&&" "==n[n.length-1-e];e++)r--;s=r}else s=O(a.text,r-a.from,e,e)+a.from,s==r&&a.number!=(e?o.doc.lines:1)?s+=e?1:-1:!e&&/[\ufe00-\ufe0f]/.test(a.text.slice(s-a.from,r-a.from))&&(s=O(a.text,s-a.from,!1,!1)+a.from);return s})),$f=t=>Qf(t,!1),Pf=t=>Qf(t,!0),Zf=(t,e)=>xf(t,(i=>{let n=i.head,{state:s}=t,r=s.doc.lineAt(n),o=s.charCategorizer(n);for(let t=null;;){if(n==(e?r.to:r.from)){n==i.head&&r.number!=(e?s.doc.lines:1)&&(n+=e?1:-1);break}let a=O(r.text,n-r.from,e)+r.from,l=r.text.slice(Math.min(n,a)-r.from,Math.max(n,a)-r.from),h=o(l);if(null!=t&&h!=t)break;" "==l&&n==i.head||(t=h),n=a}return n})),Cf=t=>Zf(t,!1);function Tf(t){let e=[],i=-1;for(let n of t.selection.ranges){let s=t.doc.lineAt(n.from),r=t.doc.lineAt(n.to);if(n.empty||n.to!=r.from||(r=t.doc.lineAt(n.to-1)),i>=s.number){let t=e[e.length-1];t.to=r.to,t.ranges.push(n)}else e.push({from:s.from,to:r.to,ranges:[n]});i=r.number+1}return e}function Af(t,e,i){if(t.readOnly)return!1;let n=[],s=[];for(let e of Tf(t)){if(i?e.to==t.doc.length:0==e.from)continue;let r=t.doc.lineAt(i?e.to+1:e.from-1),o=r.length+1;if(i){n.push({from:e.to,to:r.to},{from:e.from,insert:r.text+t.lineBreak});for(let i of e.ranges)s.push(Y.range(Math.min(t.doc.length,i.anchor+o),Math.min(t.doc.length,i.head+o)))}else{n.push({from:r.from,to:e.from},{from:e.to,insert:t.lineBreak+r.text});for(let t of e.ranges)s.push(Y.range(t.anchor-o,t.head-o))}}return!!n.length&&(e(t.update({changes:n,scrollIntoView:!0,selection:Y.create(s,t.selection.mainIndex),userEvent:"move.line"})),!0)}function Rf(t,e,i){if(t.readOnly)return!1;let n=[];for(let e of Tf(t))i?n.push({from:e.from,insert:t.doc.slice(e.from,e.to)+t.lineBreak}):n.push({from:e.to,insert:t.lineBreak+t.doc.slice(e.from,e.to)});return e(t.update({changes:n,scrollIntoView:!0,userEvent:"input.copyline"})),!0}const Xf=Yf(!1);function Yf(t){return({state:i,dispatch:n})=>{if(i.readOnly)return!1;let s=i.changeByRange((n=>{let{from:s,to:r}=n,o=i.doc.lineAt(s),a=!t&&s==r&&function(t,e){if(/\(\)|\[\]|\{\}/.test(t.sliceDoc(e-1,e+1)))return{from:e,to:e};let i,n=cl(t).resolveInner(e),s=n.childBefore(e),r=n.childAfter(e);return s&&r&&s.to<=e&&r.from>=e&&(i=s.type.prop(Jo.closedBy))&&i.indexOf(r.name)>-1&&t.doc.lineAt(s.to).from==t.doc.lineAt(r.from).from&&!/\S/.test(t.sliceDoc(s.to,r.from))?{from:s.to,to:r.from}:null}(i,s);t&&(s=r=(r<=o.to?o:i.doc.lineAt(r)).to);let l=new Zl(i,{simulateBreak:s,simulateDoubleBreak:!!a}),h=Pl(l,s);for(null==h&&(h=It(/^\s*/.exec(i.doc.lineAt(s).text)[0],i.tabSize));r<o.to&&/\s/.test(o.text[r-o.from]);)r++;a?({from:s,to:r}=a):s>o.from&&s<o.from+100&&!/\S/.test(o.text.slice(0,s))&&(s=o.from);let c=["",$l(i,h)];return a&&c.push($l(i,l.lineIndent(o.from,-1))),{changes:{from:s,to:r,insert:e.of(c)},range:Y.cursor(s+1+c[1].length)}}));return n(i.update(s,{scrollIntoView:!0,userEvent:"input"})),!0}}function Wf(t,e){let i=-1;return t.changeByRange((n=>{let s=[];for(let r=n.from;r<=n.to;){let o=t.doc.lineAt(r);o.number>i&&(n.empty||n.to>o.from)&&(e(o,s,n),i=o.number),r=o.to+1}let r=t.changes(s);return{changes:s,range:Y.range(r.mapPos(n.anchor,1),r.mapPos(n.head,1))}}))}const Mf=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:t=>zc(t,(e=>Jc(t.state,e,!Lc(t)))),shift:t=>lf(t,(e=>Jc(t.state,e,!Lc(t))))},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:t=>zc(t,(e=>Jc(t.state,e,Lc(t)))),shift:t=>lf(t,(e=>Jc(t.state,e,Lc(t))))},{key:"Alt-ArrowUp",run:({state:t,dispatch:e})=>Af(t,e,!1)},{key:"Shift-Alt-ArrowUp",run:({state:t,dispatch:e})=>Rf(t,e,!1)},{key:"Alt-ArrowDown",run:({state:t,dispatch:e})=>Af(t,e,!0)},{key:"Shift-Alt-ArrowDown",run:({state:t,dispatch:e})=>Rf(t,e,!0)},{key:"Escape",run:({state:t,dispatch:e})=>{let i=t.selection,n=null;return i.ranges.length>1?n=Y.create([i.main]):i.main.empty||(n=Y.create([Y.cursor(i.main.head)])),!!n&&(e(Ic(t,n)),!0)}},{key:"Mod-Enter",run:Yf(!0)},{key:"Alt-l",mac:"Ctrl-l",run:({state:t,dispatch:e})=>{let i=Tf(t).map((({from:e,to:i})=>Y.range(e,Math.min(i+1,t.doc.length))));return e(t.update({selection:Y.create(i),userEvent:"select"})),!0}},{key:"Mod-i",run:({state:t,dispatch:e})=>{let i=Vc(t.selection,(e=>{var i;for(let n=cl(t).resolveStack(e.from,1);n;n=n.next){let{node:t}=n;if((t.from<e.from&&t.to>=e.to||t.to>e.to&&t.from<=e.from)&&(null===(i=t.parent)||void 0===i?void 0:i.parent))return Y.range(t.to,t.from)}return e}));return e(Ic(t,i)),!0},preventDefault:!0},{key:"Mod-[",run:({state:t,dispatch:e})=>!t.readOnly&&(e(t.update(Wf(t,((e,i)=>{let n=/^\s*/.exec(e.text)[0];if(!n)return;let s=It(n,t.tabSize),r=0,o=$l(t,Math.max(0,s-Ql(t)));for(;r<n.length&&r<o.length&&n.charCodeAt(r)==o.charCodeAt(r);)r++;i.push({from:e.from+r,to:e.from+n.length,insert:o.slice(r)})})),{userEvent:"delete.dedent"})),!0)},{key:"Mod-]",run:({state:t,dispatch:e})=>!t.readOnly&&(e(t.update(Wf(t,((e,i)=>{i.push({from:e.from,insert:t.facet(kl)})})),{userEvent:"input.indent"})),!0)},{key:"Mod-Alt-\\",run:({state:t,dispatch:e})=>{if(t.readOnly)return!1;let i=Object.create(null),n=new Zl(t,{overrideIndentation:t=>{let e=i[t];return null==e?-1:e}}),s=Wf(t,((e,s,r)=>{let o=Pl(n,e.from);if(null==o)return;/\S/.test(e.text)||(o=0);let a=/^\s*/.exec(e.text)[0],l=$l(t,o);(a!=l||r.from<e.from+a.length)&&(i[e.from]=o,s.push({from:e.from,to:e.from+a.length,insert:l}))}));return s.changes.empty||e(t.update(s,{userEvent:"indent"})),!0}},{key:"Shift-Mod-k",run:t=>{if(t.state.readOnly)return!1;let{state:e}=t,i=e.changes(Tf(e).map((({from:t,to:i})=>(t>0?t--:i<e.doc.length&&i++,{from:t,to:i})))),n=Vc(e.selection,(e=>t.moveVertically(e,!0))).map(i);return t.dispatch({changes:i,selection:n,scrollIntoView:!0,userEvent:"delete.line"}),!0}},{key:"Shift-Mod-\\",run:({state:t,dispatch:e})=>function(t,e,i){let n=!1,s=Vc(t.selection,(e=>{let s=jh(t,e.head,-1)||jh(t,e.head,1)||e.head>0&&jh(t,e.head-1,1)||e.head<t.doc.length&&jh(t,e.head+1,-1);if(!s||!s.end)return e;n=!0;let r=s.start.from==e.head?s.end.to:s.end.from;return i?Y.range(e.anchor,r):Y.cursor(r)}));return!!n&&(e(Ic(t,s)),!0)}(t,e,!1)},{key:"Mod-/",run:t=>{let{state:e}=t,i=e.doc.lineAt(e.selection.main.from),n=Oc(t.state,i.from);return n.line?uc(t):!!n.block&&pc(t)}},{key:"Alt-A",run:dc}].concat([{key:"ArrowLeft",run:Nc,shift:cf,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:t=>Hc(t,!Lc(t)),shift:t=>uf(t,!Lc(t)),preventDefault:!0},{mac:"Cmd-ArrowLeft",run:t=>zc(t,(e=>af(t,e,!Lc(t)))),shift:t=>lf(t,(e=>af(t,e,!Lc(t)))),preventDefault:!0},{key:"ArrowRight",run:Uc,shift:ff,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:t=>Hc(t,Lc(t)),shift:t=>uf(t,Lc(t)),preventDefault:!0},{mac:"Cmd-ArrowRight",run:t=>zc(t,(e=>af(t,e,Lc(t)))),shift:t=>lf(t,(e=>af(t,e,Lc(t)))),preventDefault:!0},{key:"ArrowUp",run:tf,shift:pf,preventDefault:!0},{mac:"Cmd-ArrowUp",run:vf,shift:yf},{mac:"Ctrl-ArrowUp",run:rf,shift:mf},{key:"ArrowDown",run:ef,shift:Of,preventDefault:!0},{mac:"Cmd-ArrowDown",run:bf,shift:Sf},{mac:"Ctrl-ArrowDown",run:of,shift:wf},{key:"PageUp",run:rf,shift:mf},{key:"PageDown",run:of,shift:wf},{key:"Home",run:t=>zc(t,(e=>af(t,e,!1))),shift:t=>lf(t,(e=>af(t,e,!1))),preventDefault:!0},{key:"Mod-Home",run:vf,shift:yf},{key:"End",run:t=>zc(t,(e=>af(t,e,!0))),shift:t=>lf(t,(e=>af(t,e,!0))),preventDefault:!0},{key:"Mod-End",run:bf,shift:Sf},{key:"Enter",run:Xf},{key:"Mod-a",run:({state:t,dispatch:e})=>(e(t.update({selection:{anchor:0,head:t.doc.length},userEvent:"select"})),!0)},{key:"Backspace",run:$f,shift:$f},{key:"Delete",run:Pf},{key:"Mod-Backspace",mac:"Alt-Backspace",run:Cf},{key:"Mod-Delete",mac:"Alt-Delete",run:t=>Zf(t,!0)},{mac:"Mod-Backspace",run:t=>xf(t,(e=>{let i=t.moveToLineBoundary(e,!1).head;return e.head>i?i:Math.max(0,e.head-1)}))},{mac:"Mod-Delete",run:t=>xf(t,(e=>{let i=t.moveToLineBoundary(e,!0).head;return e.head<i?i:Math.min(t.state.doc.length,e.head+1)}))}].concat([{key:"Ctrl-b",run:Nc,shift:cf,preventDefault:!0},{key:"Ctrl-f",run:Uc,shift:ff},{key:"Ctrl-p",run:tf,shift:pf},{key:"Ctrl-n",run:ef,shift:Of},{key:"Ctrl-a",run:t=>zc(t,(e=>Y.cursor(t.lineBlockAt(e.head).from,1))),shift:t=>lf(t,(e=>Y.cursor(t.lineBlockAt(e.head).from)))},{key:"Ctrl-e",run:t=>zc(t,(e=>Y.cursor(t.lineBlockAt(e.head).to,-1))),shift:t=>lf(t,(e=>Y.cursor(t.lineBlockAt(e.head).to)))},{key:"Ctrl-d",run:Pf},{key:"Ctrl-h",run:$f},{key:"Ctrl-k",run:t=>xf(t,(e=>{let i=t.lineBlockAt(e.head).to;return e.head<i?i:Math.min(t.state.doc.length,e.head+1)}))},{key:"Ctrl-Alt-h",run:Cf},{key:"Ctrl-o",run:({state:t,dispatch:i})=>{if(t.readOnly)return!1;let n=t.changeByRange((t=>({changes:{from:t.from,to:t.to,insert:e.of(["",""])},range:Y.cursor(t.from)})));return i(t.update(n,{scrollIntoView:!0,userEvent:"input"})),!0}},{key:"Ctrl-t",run:({state:t,dispatch:e})=>{if(t.readOnly)return!1;let i=t.changeByRange((e=>{if(!e.empty||0==e.from||e.from==t.doc.length)return{range:e};let i=e.from,n=t.doc.lineAt(i),s=i==n.from?i-1:O(n.text,i-n.from,!1)+n.from,r=i==n.to?i+1:O(n.text,i-n.from,!0)+n.from;return{changes:{from:s,to:r,insert:t.doc.slice(i,r).append(t.doc.slice(s,i))},range:Y.cursor(r)}}));return!i.changes.empty&&(e(t.update(i,{scrollIntoView:!0,userEvent:"move.character"})),!0)}},{key:"Ctrl-v",run:of}].map((t=>({mac:t.key,run:t.run,shift:t.shift})))));function jf(){var t=arguments[0];"string"==typeof t&&(t=document.createElement(t));var e=1,i=arguments[1];if(i&&"object"==typeof i&&null==i.nodeType&&!Array.isArray(i)){for(var n in i)if(Object.prototype.hasOwnProperty.call(i,n)){var s=i[n];"string"==typeof s?t.setAttribute(n,s):null!=s&&(t[n]=s)}e++}for(;e<arguments.length;e++)Df(t,arguments[e]);return t}function Df(t,e){if("string"==typeof e)t.appendChild(document.createTextNode(e));else if(null==e);else if(null!=e.nodeType)t.appendChild(e);else{if(!Array.isArray(e))throw new RangeError("Unsupported child node: "+e);for(var i=0;i<e.length;i++)Df(t,e[i])}}const Ef="function"==typeof String.prototype.normalize?t=>t.normalize("NFKD"):t=>t;class qf{constructor(t,e,i=0,n=t.length,s,r){this.test=r,this.value={from:0,to:0},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=t.iterRange(i,n),this.bufferStart=i,this.normalize=s?t=>s(Ef(t)):Ef,this.query=this.normalize(e)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return b(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let t=this.peek();if(t<0)return this.done=!0,this;let e=y(t),i=this.bufferStart+this.bufferPos;this.bufferPos+=S(t);let n=this.normalize(e);for(let t=0,s=i;;t++){let r=n.charCodeAt(t),o=this.match(r,s);if(t==n.length-1){if(o)return this.value=o,this;break}s==i&&t<e.length&&e.charCodeAt(t)==r&&s++}}}match(t,e){let i=null;for(let n=0;n<this.matches.length;n+=2){let s=this.matches[n],r=!1;this.query.charCodeAt(s)==t&&(s==this.query.length-1?i={from:this.matches[n+1],to:e+1}:(this.matches[n]++,r=!0)),r||(this.matches.splice(n,2),n-=2)}return this.query.charCodeAt(0)==t&&(1==this.query.length?i={from:e,to:e+1}:this.matches.push(1,e)),i&&this.test&&!this.test(i.from,i.to,this.buffer,this.bufferStart)&&(i=null),i}}"undefined"!=typeof Symbol&&(qf.prototype[Symbol.iterator]=function(){return this});const _f={from:-1,to:-1,match:/.*/.exec("")},Vf="gm"+(null==/x/.unicode?"":"u");class If{constructor(t,e,i,n=0,s=t.length){if(this.text=t,this.to=s,this.curLine="",this.done=!1,this.value=_f,/\\[sWDnr]|\n|\r|\[\^/.test(e))return new Gf(t,e,i,n,s);this.re=new RegExp(e,Vf+((null==i?void 0:i.ignoreCase)?"i":"")),this.test=null==i?void 0:i.test,this.iter=t.iter();let r=t.lineAt(n);this.curLineStart=r.from,this.matchPos=Lf(t,n),this.getLine(this.curLineStart)}getLine(t){this.iter.next(t),this.iter.lineBreak?this.curLine="":(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let t=this.matchPos-this.curLineStart;;){this.re.lastIndex=t;let e=this.matchPos<=this.to&&this.re.exec(this.curLine);if(e){let i=this.curLineStart+e.index,n=i+e[0].length;if(this.matchPos=Lf(this.text,n+(i==n?1:0)),i==this.curLineStart+this.curLine.length&&this.nextLine(),(i<n||i>this.value.to)&&(!this.test||this.test(i,n,e)))return this.value={from:i,to:n,match:e},this;t=this.matchPos-this.curLineStart}else{if(!(this.curLineStart+this.curLine.length<this.to))return this.done=!0,this;this.nextLine(),t=0}}}}const zf=new WeakMap;class Bf{constructor(t,e){this.from=t,this.text=e}get to(){return this.from+this.text.length}static get(t,e,i){let n=zf.get(t);if(!n||n.from>=i||n.to<=e){let n=new Bf(e,t.sliceString(e,i));return zf.set(t,n),n}if(n.from==e&&n.to==i)return n;let{text:s,from:r}=n;return r>e&&(s=t.sliceString(e,r)+s,r=e),n.to<i&&(s+=t.sliceString(n.to,i)),zf.set(t,new Bf(r,s)),new Bf(e,s.slice(e-r,i-r))}}class Gf{constructor(t,e,i,n,s){this.text=t,this.to=s,this.done=!1,this.value=_f,this.matchPos=Lf(t,n),this.re=new RegExp(e,Vf+((null==i?void 0:i.ignoreCase)?"i":"")),this.test=null==i?void 0:i.test,this.flat=Bf.get(t,n,this.chunkEnd(n+5e3))}chunkEnd(t){return t>=this.to?this.to:this.text.lineAt(t).to}next(){for(;;){let t=this.re.lastIndex=this.matchPos-this.flat.from,e=this.re.exec(this.flat.text);if(e&&!e[0]&&e.index==t&&(this.re.lastIndex=t+1,e=this.re.exec(this.flat.text)),e){let t=this.flat.from+e.index,i=t+e[0].length;if((this.flat.to>=this.to||e.index+e[0].length<=this.flat.text.length-10)&&(!this.test||this.test(t,i,e)))return this.value={from:t,to:i,match:e},this.matchPos=Lf(this.text,i+(t==i?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=Bf.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+2*this.flat.text.length))}}}function Lf(t,e){if(e>=t.length)return e;let i,n=t.lineAt(e);for(;e<n.to&&(i=n.text.charCodeAt(e-n.from))>=56320&&i<57344;)e++;return e}function Nf(t){let e=jf("input",{class:"cm-textfield",name:"line",value:String(t.state.doc.lineAt(t.state.selection.main.head).number)});function i(){let i=/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(e.value);if(!i)return;let{state:n}=t,s=n.doc.lineAt(n.selection.main.head),[,r,o,a,l]=i,h=a?+a.slice(1):0,c=o?+o:s.number;if(o&&l){let t=c/100;r&&(t=t*("-"==r?-1:1)+s.number/n.doc.lines),c=Math.round(n.doc.lines*t)}else o&&r&&(c=c*("-"==r?-1:1)+s.number);let f=n.doc.line(Math.max(1,Math.min(n.doc.lines,c))),u=Y.cursor(f.from+Math.max(0,Math.min(h,f.length)));t.dispatch({effects:[Uf.of(!1),Gs.scrollIntoView(u.from,{y:"center"})],selection:u}),t.focus()}return{dom:jf("form",{class:"cm-gotoLine",onkeydown:e=>{27==e.keyCode?(e.preventDefault(),t.dispatch({effects:Uf.of(!1)}),t.focus()):13==e.keyCode&&(e.preventDefault(),i())},onsubmit:t=>{t.preventDefault(),i()}},jf("label",t.state.phrase("Go to line"),": ",e)," ",jf("button",{class:"cm-button",type:"submit"},t.state.phrase("go")))}}"undefined"!=typeof Symbol&&(If.prototype[Symbol.iterator]=Gf.prototype[Symbol.iterator]=function(){return this});const Uf=dt.define(),Hf=z.define({create:()=>!0,update(t,e){for(let i of e.effects)i.is(Uf)&&(t=i.value);return t},provide:t=>vo.from(t,(t=>t?Nf:null))}),Ff=Gs.baseTheme({".cm-panel.cm-gotoLine":{padding:"2px 6px 4px","& label":{fontSize:"80%"}}}),Jf={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},Kf=j.define({combine:t=>$t(t,Jf,{highlightWordAroundCursor:(t,e)=>t||e,minSelectionLength:Math.min,maxMatches:Math.min})});function tu(t){let e=[ru,su];return t&&e.push(Kf.of(t)),e}const eu=si.mark({class:"cm-selectionMatch"}),iu=si.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function nu(t,e,i,n){return!(0!=i&&t(e.sliceDoc(i-1,i))==yt.Word||n!=e.doc.length&&t(e.sliceDoc(n,n+1))==yt.Word)}const su=Ni.fromClass(class{constructor(t){this.decorations=this.getDeco(t)}update(t){(t.selectionSet||t.docChanged||t.viewportChanged)&&(this.decorations=this.getDeco(t.view))}getDeco(t){let e=t.state.facet(Kf),{state:i}=t,n=i.selection;if(n.ranges.length>1)return si.none;let s,r=n.main,o=null;if(r.empty){if(!e.highlightWordAroundCursor)return si.none;let t=i.wordAt(r.head);if(!t)return si.none;o=i.charCategorizer(r.head),s=i.sliceDoc(t.from,t.to)}else{let t=r.to-r.from;if(t<e.minSelectionLength||t>200)return si.none;if(e.wholeWords){if(s=i.sliceDoc(r.from,r.to),o=i.charCategorizer(r.head),!nu(o,i,r.from,r.to)||!function(t,e,i,n){return t(e.sliceDoc(i,i+1))==yt.Word&&t(e.sliceDoc(n-1,n))==yt.Word}(o,i,r.from,r.to))return si.none}else if(s=i.sliceDoc(r.from,r.to).trim(),!s)return si.none}let a=[];for(let n of t.visibleRanges){let t=new qf(i.doc,s,n.from,n.to);for(;!t.next().done;){let{from:n,to:s}=t.value;if((!o||nu(o,i,n,s))&&(r.empty&&n<=r.from&&s>=r.to?a.push(iu.range(n,s)):(n>=r.to||s<=r.from)&&a.push(eu.range(n,s)),a.length>e.maxMatches))return si.none}}return si.set(a)}},{decorations:t=>t.decorations}),ru=Gs.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}});const ou=j.define({combine:t=>$t(t,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new Wu(t),scrollToMatch:t=>Gs.scrollIntoView(t)})});class au{constructor(t){this.search=t.search,this.caseSensitive=!!t.caseSensitive,this.literal=!!t.literal,this.regexp=!!t.regexp,this.replace=t.replace||"",this.valid=!!this.search&&(!this.regexp||function(t){try{return new RegExp(t,Vf),!0}catch(t){return!1}}(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!t.wholeWord}unquote(t){return this.literal?t:t.replace(/\\([nrt\\])/g,((t,e)=>"n"==e?"\n":"r"==e?"\r":"t"==e?"\t":"\\"))}eq(t){return this.search==t.search&&this.replace==t.replace&&this.caseSensitive==t.caseSensitive&&this.regexp==t.regexp&&this.wholeWord==t.wholeWord}create(){return this.regexp?new pu(this):new cu(this)}getCursor(t,e=0,i){let n=t.doc?t:Qt.create({doc:t});return null==i&&(i=n.doc.length),this.regexp?fu(this,n,e,i):hu(this,n,e,i)}}class lu{constructor(t){this.spec=t}}function hu(t,e,i,n){return new qf(e.doc,t.unquoted,i,n,t.caseSensitive?void 0:t=>t.toLowerCase(),t.wholeWord?function(t,e){return(i,n,s,r)=>((r>i||r+s.length<n)&&(r=Math.max(0,i-2),s=t.sliceString(r,Math.min(t.length,n+2))),!(e(uu(s,i-r))==yt.Word&&e(du(s,i-r))==yt.Word||e(du(s,n-r))==yt.Word&&e(uu(s,n-r))==yt.Word))}(e.doc,e.charCategorizer(e.selection.main.head)):void 0)}class cu extends lu{constructor(t){super(t)}nextMatch(t,e,i){let n=hu(this.spec,t,i,t.doc.length).nextOverlapping();return n.done&&(n=hu(this.spec,t,0,e).nextOverlapping()),n.done?null:n.value}prevMatchInRange(t,e,i){for(let n=i;;){let i=Math.max(e,n-1e4-this.spec.unquoted.length),s=hu(this.spec,t,i,n),r=null;for(;!s.nextOverlapping().done;)r=s.value;if(r)return r;if(i==e)return null;n-=1e4}}prevMatch(t,e,i){return this.prevMatchInRange(t,0,e)||this.prevMatchInRange(t,i,t.doc.length)}getReplacement(t){return this.spec.unquote(this.spec.replace)}matchAll(t,e){let i=hu(this.spec,t,0,t.doc.length),n=[];for(;!i.next().done;){if(n.length>=e)return null;n.push(i.value)}return n}highlight(t,e,i,n){let s=hu(this.spec,t,Math.max(0,e-this.spec.unquoted.length),Math.min(i+this.spec.unquoted.length,t.doc.length));for(;!s.next().done;)n(s.value.from,s.value.to)}}function fu(t,e,i,n){return new If(e.doc,t.search,{ignoreCase:!t.caseSensitive,test:t.wholeWord?(s=e.charCategorizer(e.selection.main.head),(t,e,i)=>!i[0].length||(s(uu(i.input,i.index))!=yt.Word||s(du(i.input,i.index))!=yt.Word)&&(s(du(i.input,i.index+i[0].length))!=yt.Word||s(uu(i.input,i.index+i[0].length))!=yt.Word)):void 0},i,n);var s}function uu(t,e){return t.slice(O(t,e,!1),e)}function du(t,e){return t.slice(e,O(t,e))}class pu extends lu{nextMatch(t,e,i){let n=fu(this.spec,t,i,t.doc.length).next();return n.done&&(n=fu(this.spec,t,0,e).next()),n.done?null:n.value}prevMatchInRange(t,e,i){for(let n=1;;n++){let s=Math.max(e,i-1e4*n),r=fu(this.spec,t,s,i),o=null;for(;!r.next().done;)o=r.value;if(o&&(s==e||o.from>s+10))return o;if(s==e)return null}}prevMatch(t,e,i){return this.prevMatchInRange(t,0,e)||this.prevMatchInRange(t,i,t.doc.length)}getReplacement(t){return this.spec.unquote(this.spec.replace).replace(/\$([$&\d+])/g,((e,i)=>"$"==i?"$":"&"==i?t.match[0]:"0"!=i&&+i<t.match.length?t.match[i]:e))}matchAll(t,e){let i=fu(this.spec,t,0,t.doc.length),n=[];for(;!i.next().done;){if(n.length>=e)return null;n.push(i.value)}return n}highlight(t,e,i,n){let s=fu(this.spec,t,Math.max(0,e-250),Math.min(i+250,t.doc.length));for(;!s.next().done;)n(s.value.from,s.value.to)}}const Ou=dt.define(),gu=dt.define(),mu=z.define({create:t=>new wu(Cu(t).create(),null),update(t,e){for(let i of e.effects)i.is(Ou)?t=new wu(i.value.create(),t.panel):i.is(gu)&&(t=new wu(t.query,i.value?Zu:null));return t},provide:t=>vo.from(t,(t=>t.panel))});class wu{constructor(t,e){this.query=t,this.panel=e}}const vu=si.mark({class:"cm-searchMatch"}),bu=si.mark({class:"cm-searchMatch cm-searchMatch-selected"}),yu=Ni.fromClass(class{constructor(t){this.view=t,this.decorations=this.highlight(t.state.field(mu))}update(t){let e=t.state.field(mu);(e!=t.startState.field(mu)||t.docChanged||t.selectionSet||t.viewportChanged)&&(this.decorations=this.highlight(e))}highlight({query:t,panel:e}){if(!e||!t.spec.valid)return si.none;let{view:i}=this,n=new Rt;for(let e=0,s=i.visibleRanges,r=s.length;e<r;e++){let{from:o,to:a}=s[e];for(;e<r-1&&a>s[e+1].from-500;)a=s[++e].to;t.highlight(i.state,o,a,((t,e)=>{let s=i.state.selection.ranges.some((i=>i.from==t&&i.to==e));n.add(t,e,s?bu:vu)}))}return n.finish()}},{decorations:t=>t.decorations});function Su(t){return e=>{let i=e.state.field(mu,!1);return i&&i.query.spec.valid?t(e,i):Ru(e)}}const xu=Su(((t,{query:e})=>{let{to:i}=t.state.selection.main,n=e.nextMatch(t.state,i,i);if(!n)return!1;let s=Y.single(n.from,n.to),r=t.state.facet(ou);return t.dispatch({selection:s,effects:[Eu(t,n),r.scrollToMatch(s.main,t)],userEvent:"select.search"}),Au(t),!0})),ku=Su(((t,{query:e})=>{let{state:i}=t,{from:n}=i.selection.main,s=e.prevMatch(i,n,n);if(!s)return!1;let r=Y.single(s.from,s.to),o=t.state.facet(ou);return t.dispatch({selection:r,effects:[Eu(t,s),o.scrollToMatch(r.main,t)],userEvent:"select.search"}),Au(t),!0})),Qu=Su(((t,{query:e})=>{let i=e.matchAll(t.state,1e3);return!(!i||!i.length)&&(t.dispatch({selection:Y.create(i.map((t=>Y.range(t.from,t.to)))),userEvent:"select.search.matches"}),!0)})),$u=Su(((t,{query:e})=>{let{state:i}=t,{from:n,to:s}=i.selection.main;if(i.readOnly)return!1;let r=e.nextMatch(i,n,n);if(!r)return!1;let o,a,l=[],h=[];if(r.from==n&&r.to==s&&(a=i.toText(e.getReplacement(r)),l.push({from:r.from,to:r.to,insert:a}),r=e.nextMatch(i,r.from,r.to),h.push(Gs.announce.of(i.phrase("replaced match on line $",i.doc.lineAt(n).number)+"."))),r){let e=0==l.length||l[0].from>=r.to?0:r.to-r.from-a.length;o=Y.single(r.from-e,r.to-e),h.push(Eu(t,r)),h.push(i.facet(ou).scrollToMatch(o.main,t))}return t.dispatch({changes:l,selection:o,effects:h,userEvent:"input.replace"}),!0})),Pu=Su(((t,{query:e})=>{if(t.state.readOnly)return!1;let i=e.matchAll(t.state,1e9).map((t=>{let{from:i,to:n}=t;return{from:i,to:n,insert:e.getReplacement(t)}}));if(!i.length)return!1;let n=t.state.phrase("replaced $ matches",i.length)+".";return t.dispatch({changes:i,effects:Gs.announce.of(n),userEvent:"input.replace.all"}),!0}));function Zu(t){return t.state.facet(ou).createPanel(t)}function Cu(t,e){var i,n,s,r,o;let a=t.selection.main,l=a.empty||a.to>a.from+100?"":t.sliceDoc(a.from,a.to);if(e&&!l)return e;let h=t.facet(ou);return new au({search:(null!==(i=null==e?void 0:e.literal)&&void 0!==i?i:h.literal)?l:l.replace(/\n/g,"\\n"),caseSensitive:null!==(n=null==e?void 0:e.caseSensitive)&&void 0!==n?n:h.caseSensitive,literal:null!==(s=null==e?void 0:e.literal)&&void 0!==s?s:h.literal,regexp:null!==(r=null==e?void 0:e.regexp)&&void 0!==r?r:h.regexp,wholeWord:null!==(o=null==e?void 0:e.wholeWord)&&void 0!==o?o:h.wholeWord})}function Tu(t){let e=Oo(t,Zu);return e&&e.dom.querySelector("[main-field]")}function Au(t){let e=Tu(t);e&&e==t.root.activeElement&&e.select()}const Ru=t=>{let e=t.state.field(mu,!1);if(e&&e.panel){let i=Tu(t);if(i&&i!=t.root.activeElement){let n=Cu(t.state,e.query.spec);n.valid&&t.dispatch({effects:Ou.of(n)}),i.focus(),i.select()}}else t.dispatch({effects:[gu.of(!0),e?Ou.of(Cu(t.state,e.query.spec)):dt.appendConfig.of(_u)]});return!0},Xu=t=>{let e=t.state.field(mu,!1);if(!e||!e.panel)return!1;let i=Oo(t,Zu);return i&&i.dom.contains(t.root.activeElement)&&t.focus(),t.dispatch({effects:gu.of(!1)}),!0},Yu=[{key:"Mod-f",run:Ru,scope:"editor search-panel"},{key:"F3",run:xu,shift:ku,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:xu,shift:ku,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:Xu,scope:"editor search-panel"},{key:"Mod-Shift-l",run:({state:t,dispatch:e})=>{let i=t.selection;if(i.ranges.length>1||i.main.empty)return!1;let{from:n,to:s}=i.main,r=[],o=0;for(let e=new qf(t.doc,t.sliceDoc(n,s));!e.next().done;){if(r.length>1e3)return!1;e.value.from==n&&(o=r.length),r.push(Y.range(e.value.from,e.value.to))}return e(t.update({selection:Y.create(r,o),userEvent:"select.search.matches"})),!0}},{key:"Mod-Alt-g",run:t=>{let e=Oo(t,Nf);if(!e){let i=[Uf.of(!0)];null==t.state.field(Hf,!1)&&i.push(dt.appendConfig.of([Hf,Ff])),t.dispatch({effects:i}),e=Oo(t,Nf)}return e&&e.dom.querySelector("input").select(),!0}},{key:"Mod-d",run:({state:t,dispatch:e})=>{let{ranges:i}=t.selection;if(i.some((t=>t.from===t.to)))return(({state:t,dispatch:e})=>{let{selection:i}=t,n=Y.create(i.ranges.map((e=>t.wordAt(e.head)||Y.cursor(e.head))),i.mainIndex);return!n.eq(i)&&(e(t.update({selection:n})),!0)})({state:t,dispatch:e});let n=t.sliceDoc(i[0].from,i[0].to);if(t.selection.ranges.some((e=>t.sliceDoc(e.from,e.to)!=n)))return!1;let s=function(t,e){let{main:i,ranges:n}=t.selection,s=t.wordAt(i.head),r=s&&s.from==i.from&&s.to==i.to;for(let i=!1,s=new qf(t.doc,e,n[n.length-1].to);;){if(s.next(),!s.done){if(i&&n.some((t=>t.from==s.value.from)))continue;if(r){let e=t.wordAt(s.value.from);if(!e||e.from!=s.value.from||e.to!=s.value.to)continue}return s.value}if(i)return null;s=new qf(t.doc,e,0,Math.max(0,n[n.length-1].from-1)),i=!0}}(t,n);return!!s&&(e(t.update({selection:t.selection.addRange(Y.range(s.from,s.to),!1),effects:Gs.scrollIntoView(s.to)})),!0)},preventDefault:!0}];class Wu{constructor(t){this.view=t;let e=this.query=t.state.field(mu).query.spec;function i(t,e,i){return jf("button",{class:"cm-button",name:t,onclick:e,type:"button"},i)}this.commit=this.commit.bind(this),this.searchField=jf("input",{value:e.search,placeholder:Mu(t,"Find"),"aria-label":Mu(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=jf("input",{value:e.replace,placeholder:Mu(t,"Replace"),"aria-label":Mu(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=jf("input",{type:"checkbox",name:"case",form:"",checked:e.caseSensitive,onchange:this.commit}),this.reField=jf("input",{type:"checkbox",name:"re",form:"",checked:e.regexp,onchange:this.commit}),this.wordField=jf("input",{type:"checkbox",name:"word",form:"",checked:e.wholeWord,onchange:this.commit}),this.dom=jf("div",{onkeydown:t=>this.keydown(t),class:"cm-search"},[this.searchField,i("next",(()=>xu(t)),[Mu(t,"next")]),i("prev",(()=>ku(t)),[Mu(t,"previous")]),i("select",(()=>Qu(t)),[Mu(t,"all")]),jf("label",null,[this.caseField,Mu(t,"match case")]),jf("label",null,[this.reField,Mu(t,"regexp")]),jf("label",null,[this.wordField,Mu(t,"by word")]),...t.state.readOnly?[]:[jf("br"),this.replaceField,i("replace",(()=>$u(t)),[Mu(t,"replace")]),i("replaceAll",(()=>Pu(t)),[Mu(t,"replace all")])],jf("button",{name:"close",onclick:()=>Xu(t),"aria-label":Mu(t,"close"),type:"button"},["×"])])}commit(){let t=new au({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});t.eq(this.query)||(this.query=t,this.view.dispatch({effects:Ou.of(t)}))}keydown(t){nr(this.view,t,"search-panel")?t.preventDefault():13==t.keyCode&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?ku:xu)(this.view)):13==t.keyCode&&t.target==this.replaceField&&(t.preventDefault(),$u(this.view))}update(t){for(let e of t.transactions)for(let t of e.effects)t.is(Ou)&&!t.value.eq(this.query)&&this.setQuery(t.value)}setQuery(t){this.query=t,this.searchField.value=t.search,this.replaceField.value=t.replace,this.caseField.checked=t.caseSensitive,this.reField.checked=t.regexp,this.wordField.checked=t.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(ou).top}}function Mu(t,e){return t.state.phrase(e)}const ju=30,Du=/[\s\.,:;?!]/;function Eu(t,{from:e,to:i}){let n=t.state.doc.lineAt(e),s=t.state.doc.lineAt(i).to,r=Math.max(n.from,e-ju),o=Math.min(s,i+ju),a=t.state.sliceDoc(r,o);if(r!=n.from)for(let t=0;t<ju;t++)if(!Du.test(a[t+1])&&Du.test(a[t])){a=a.slice(t);break}if(o!=s)for(let t=a.length-1;t>a.length-ju;t--)if(!Du.test(a[t-1])&&Du.test(a[t])){a=a.slice(0,t);break}return Gs.announce.of(`${t.state.phrase("current match")}. ${a} ${t.state.phrase("on line")} ${n.number}.`)}const qu=Gs.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),_u=[mu,H.low(yu),qu];class Vu{constructor(t,e,i){this.state=t,this.pos=e,this.explicit=i,this.abortListeners=[]}tokenBefore(t){let e=cl(this.state).resolveInner(this.pos,-1);for(;e&&t.indexOf(e.name)<0;)e=e.parent;return e?{from:e.from,to:this.pos,text:this.state.sliceDoc(e.from,this.pos),type:e.type}:null}matchBefore(t){let e=this.state.doc.lineAt(this.pos),i=Math.max(e.from,this.pos-250),n=e.text.slice(i-e.from,this.pos-e.from),s=n.search(Lu(t,!1));return s<0?null:{from:i+s,to:this.pos,text:n.slice(s)}}get aborted(){return null==this.abortListeners}addEventListener(t,e){"abort"==t&&this.abortListeners&&this.abortListeners.push(e)}}function Iu(t){let e=Object.keys(t).join(""),i=/\w/.test(e);return i&&(e=e.replace(/\w/g,"")),`[${i?"\\w":""}${e.replace(/[^\w\s]/g,"\\$&")}]`}function zu(t){let e=t.map((t=>"string"==typeof t?{label:t}:t)),[i,n]=e.every((t=>/^\w+$/.test(t.label)))?[/\w*$/,/\w+$/]:function(t){let e=Object.create(null),i=Object.create(null);for(let{label:n}of t){e[n[0]]=!0;for(let t=1;t<n.length;t++)i[n[t]]=!0}let n=Iu(e)+Iu(i)+"*$";return[new RegExp("^"+n),new RegExp(n)]}(e);return t=>{let s=t.matchBefore(n);return s||t.explicit?{from:s?s.from:t.pos,options:e,validFor:i}:null}}class Bu{constructor(t,e,i,n){this.completion=t,this.source=e,this.match=i,this.score=n}}function Gu(t){return t.selection.main.from}function Lu(t,e){var i;let{source:n}=t,s=e&&"^"!=n[0],r="$"!=n[n.length-1];return s||r?new RegExp(`${s?"^":""}(?:${n})${r?"$":""}`,null!==(i=t.flags)&&void 0!==i?i:t.ignoreCase?"i":""):t}const Nu=ct.define();const Uu=new WeakMap;function Hu(t){if(!Array.isArray(t))return t;let e=Uu.get(t);return e||Uu.set(t,e=zu(t)),e}const Fu=dt.define(),Ju=dt.define();class Ku{constructor(t){this.pattern=t,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[],this.score=0,this.matched=[];for(let e=0;e<t.length;){let i=b(t,e),n=S(i);this.chars.push(i);let s=t.slice(e,e+n),r=s.toUpperCase();this.folded.push(b(r==s?s.toLowerCase():r,0)),e+=n}this.astral=t.length!=this.chars.length}ret(t,e){return this.score=t,this.matched=e,!0}match(t){if(0==this.pattern.length)return this.ret(-100,[]);if(t.length<this.pattern.length)return!1;let{chars:e,folded:i,any:n,precise:s,byWord:r}=this;if(1==e.length){let n=b(t,0),s=S(n),r=s==t.length?0:-100;if(n==e[0]);else{if(n!=i[0])return!1;r+=-200}return this.ret(r,[0,s])}let o=t.indexOf(this.pattern);if(0==o)return this.ret(t.length==this.pattern.length?0:-100,[0,this.pattern.length]);let a=e.length,l=0;if(o<0){for(let s=0,r=Math.min(t.length,200);s<r&&l<a;){let r=b(t,s);r!=e[l]&&r!=i[l]||(n[l++]=s),s+=S(r)}if(l<a)return!1}let h=0,c=0,f=!1,u=0,d=-1,p=-1,O=/[a-z]/.test(t),g=!0;for(let n=0,l=Math.min(t.length,200),m=0;n<l&&c<a;){let l=b(t,n);o<0&&(h<a&&l==e[h]&&(s[h++]=n),u<a&&(l==e[u]||l==i[u]?(0==u&&(d=n),p=n+1,u++):u=0));let w,v=l<255?l>=48&&l<=57||l>=97&&l<=122?2:l>=65&&l<=90?1:0:(w=y(l))!=w.toLowerCase()?1:w!=w.toUpperCase()?2:0;(!n||1==v&&O||0==m&&0!=v)&&(e[c]==l||i[c]==l&&(f=!0)?r[c++]=n:r.length&&(g=!1)),m=v,n+=S(l)}return c==a&&0==r[0]&&g?this.result((f?-200:0)-100,r,t):u==a&&0==d?this.ret(-200-t.length+(p==t.length?0:-100),[0,p]):o>-1?this.ret(-700-t.length,[o,o+this.pattern.length]):u==a?this.ret(-900-t.length,[d,p]):c==a?this.result((f?-200:0)-100-700+(g?0:-1100),r,t):2!=e.length&&this.result((n[0]?-700:0)-200-1100,n,t)}result(t,e,i){let n=[],s=0;for(let t of e){let e=t+(this.astral?S(b(i,t)):1);s&&n[s-1]==t?n[s-1]=e:(n[s++]=t,n[s++]=e)}return this.ret(t-i.length,n)}}const td=j.define({combine:t=>$t(t,{activateOnTyping:!0,activateOnTypingDelay:100,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,tooltipClass:()=>"",optionClass:()=>"",aboveCursor:!1,icons:!0,addToOptions:[],positionInfo:id,compareCompletions:(t,e)=>t.label.localeCompare(e.label),interactionDelay:75,updateSyncTime:100},{defaultKeymap:(t,e)=>t&&e,closeOnBlur:(t,e)=>t&&e,icons:(t,e)=>t&&e,tooltipClass:(t,e)=>i=>ed(t(i),e(i)),optionClass:(t,e)=>i=>ed(t(i),e(i)),addToOptions:(t,e)=>t.concat(e)})});function ed(t,e){return t?e?t+" "+e:t:e}function id(t,e,i,n,s,r){let o,a,l=t.textDirection==di.RTL,h=l,c=!1,f="top",u=e.left-s.left,d=s.right-e.right,p=n.right-n.left,O=n.bottom-n.top;if(h&&u<Math.min(p,d)?h=!1:!h&&d<Math.min(p,u)&&(h=!0),p<=(h?u:d))o=Math.max(s.top,Math.min(i.top,s.bottom-O))-e.top,a=Math.min(400,h?u:d);else{c=!0,a=Math.min(400,(l?e.right:s.right-e.left)-30);let t=s.bottom-e.bottom;t>=O||t>e.top?o=i.bottom-e.top:(f="bottom",o=e.bottom-i.top)}return{style:`${f}: ${o/((e.bottom-e.top)/r.offsetHeight)}px; max-width: ${a/((e.right-e.left)/r.offsetWidth)}px`,class:"cm-completionInfo-"+(c?l?"left-narrow":"right-narrow":h?"left":"right")}}function nd(t,e,i){if(t<=i)return{from:0,to:t};if(e<0&&(e=0),e<=t>>1){let t=Math.floor(e/i);return{from:t*i,to:(t+1)*i}}let n=Math.floor((t-e)/i);return{from:t-(n+1)*i,to:t-n*i}}class sd{constructor(t,e,i){this.view=t,this.stateField=e,this.applyCompletion=i,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:t=>this.placeInfo(t),key:this},this.space=null,this.currentClass="";let n=t.state.field(e),{options:s,selected:r}=n.open,o=t.state.facet(td);this.optionContent=function(t){let e=t.addToOptions.slice();return t.icons&&e.push({render(t){let e=document.createElement("div");return e.classList.add("cm-completionIcon"),t.type&&e.classList.add(...t.type.split(/\s+/g).map((t=>"cm-completionIcon-"+t))),e.setAttribute("aria-hidden","true"),e},position:20}),e.push({render(t,e,i,n){let s=document.createElement("span");s.className="cm-completionLabel";let r=t.displayLabel||t.label,o=0;for(let t=0;t<n.length;){let e=n[t++],i=n[t++];e>o&&s.appendChild(document.createTextNode(r.slice(o,e)));let a=s.appendChild(document.createElement("span"));a.appendChild(document.createTextNode(r.slice(e,i))),a.className="cm-completionMatchedText",o=i}return o<r.length&&s.appendChild(document.createTextNode(r.slice(o))),s},position:50},{render(t){if(!t.detail)return null;let e=document.createElement("span");return e.className="cm-completionDetail",e.textContent=t.detail,e},position:80}),e.sort(((t,e)=>t.position-e.position)).map((t=>t.render))}(o),this.optionClass=o.optionClass,this.tooltipClass=o.tooltipClass,this.range=nd(s.length,r,o.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.updateTooltipClass(t.state),this.dom.addEventListener("mousedown",(i=>{let{options:n}=t.state.field(e).open;for(let e,s=i.target;s&&s!=this.dom;s=s.parentNode)if("LI"==s.nodeName&&(e=/-(\d+)$/.exec(s.id))&&+e[1]<n.length)return this.applyCompletion(t,n[+e[1]]),void i.preventDefault()})),this.dom.addEventListener("focusout",(e=>{let i=t.state.field(this.stateField,!1);i&&i.tooltip&&t.state.facet(td).closeOnBlur&&e.relatedTarget!=t.contentDOM&&t.dispatch({effects:Ju.of(null)})})),this.showOptions(s,n.id)}mount(){this.updateSel()}showOptions(t,e){this.list&&this.list.remove(),this.list=this.dom.appendChild(this.createListBox(t,e,this.range)),this.list.addEventListener("scroll",(()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)}))}update(t){var e;let i=t.state.field(this.stateField),n=t.startState.field(this.stateField);if(this.updateTooltipClass(t.state),i!=n){let{options:s,selected:r,disabled:o}=i.open;n.open&&n.open.options==s||(this.range=nd(s.length,r,t.state.facet(td).maxRenderedOptions),this.showOptions(s,i.id)),this.updateSel(),o!=(null===(e=n.open)||void 0===e?void 0:e.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!o)}}updateTooltipClass(t){let e=this.tooltipClass(t);if(e!=this.currentClass){for(let t of this.currentClass.split(" "))t&&this.dom.classList.remove(t);for(let t of e.split(" "))t&&this.dom.classList.add(t);this.currentClass=e}}positioned(t){this.space=t,this.info&&this.view.requestMeasure(this.placeInfoReq)}updateSel(){let t=this.view.state.field(this.stateField),e=t.open;if((e.selected>-1&&e.selected<this.range.from||e.selected>=this.range.to)&&(this.range=nd(e.options.length,e.selected,this.view.state.facet(td).maxRenderedOptions),this.showOptions(e.options,t.id)),this.updateSelectedOption(e.selected)){this.destroyInfo();let{completion:i}=e.options[e.selected],{info:n}=i;if(!n)return;let s="string"==typeof n?document.createTextNode(n):n(i);if(!s)return;"then"in s?s.then((e=>{e&&this.view.state.field(this.stateField,!1)==t&&this.addInfoPane(e,i)})).catch((t=>zi(this.view.state,t,"completion info"))):this.addInfoPane(s,i)}}addInfoPane(t,e){this.destroyInfo();let i=this.info=document.createElement("div");if(i.className="cm-tooltip cm-completionInfo",null!=t.nodeType)i.appendChild(t),this.infoDestroy=null;else{let{dom:e,destroy:n}=t;i.appendChild(e),this.infoDestroy=n||null}this.dom.appendChild(i),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(t){let e=null;for(let i=this.list.firstChild,n=this.range.from;i;i=i.nextSibling,n++)"LI"==i.nodeName&&i.id?n==t?i.hasAttribute("aria-selected")||(i.setAttribute("aria-selected","true"),e=i):i.hasAttribute("aria-selected")&&i.removeAttribute("aria-selected"):n--;return e&&function(t,e){let i=t.getBoundingClientRect(),n=e.getBoundingClientRect(),s=i.height/t.offsetHeight;n.top<i.top?t.scrollTop-=(i.top-n.top)/s:n.bottom>i.bottom&&(t.scrollTop+=(n.bottom-i.bottom)/s)}(this.list,e),e}measureInfo(){let t=this.dom.querySelector("[aria-selected]");if(!t||!this.info)return null;let e=this.dom.getBoundingClientRect(),i=this.info.getBoundingClientRect(),n=t.getBoundingClientRect(),s=this.space;if(!s){let t=this.dom.ownerDocument.defaultView||window;s={left:0,top:0,right:t.innerWidth,bottom:t.innerHeight}}return n.top>Math.min(s.bottom,e.bottom)-10||n.bottom<Math.max(s.top,e.top)+10?null:this.view.state.facet(td).positionInfo(this.view,e,n,i,s,this.dom)}placeInfo(t){this.info&&(t?(t.style&&(this.info.style.cssText=t.style),this.info.className="cm-tooltip cm-completionInfo "+(t.class||"")):this.info.style.cssText="top: -1e6px")}createListBox(t,e,i){const n=document.createElement("ul");n.id=e,n.setAttribute("role","listbox"),n.setAttribute("aria-expanded","true"),n.setAttribute("aria-label",this.view.state.phrase("Completions"));let s=null;for(let r=i.from;r<i.to;r++){let{completion:o,match:a}=t[r],{section:l}=o;if(l){let t="string"==typeof l?l:l.name;if(t!=s&&(r>i.from||0==i.from))if(s=t,"string"!=typeof l&&l.header)n.appendChild(l.header(l));else{n.appendChild(document.createElement("completion-section")).textContent=t}}const h=n.appendChild(document.createElement("li"));h.id=e+"-"+r,h.setAttribute("role","option");let c=this.optionClass(o);c&&(h.className=c);for(let t of this.optionContent){let e=t(o,this.view.state,this.view,a);e&&h.appendChild(e)}}return i.from&&n.classList.add("cm-completionListIncompleteTop"),i.to<t.length&&n.classList.add("cm-completionListIncompleteBottom"),n}destroyInfo(){this.info&&(this.infoDestroy&&this.infoDestroy(),this.info.remove(),this.info=null)}destroy(){this.destroyInfo()}}function rd(t,e){return i=>new sd(i,t,e)}function od(t){return 100*(t.boost||0)+(t.apply?10:0)+(t.info?5:0)+(t.type?1:0)}class ad{constructor(t,e,i,n,s,r){this.options=t,this.attrs=e,this.tooltip=i,this.timestamp=n,this.selected=s,this.disabled=r}setSelected(t,e){return t==this.selected||t>=this.options.length?this:new ad(this.options,cd(e,t),this.tooltip,this.timestamp,t,this.disabled)}static build(t,e,i,n,s){let r=function(t,e){let i=[],n=null,s=t=>{i.push(t);let{section:e}=t.completion;if(e){n||(n=[]);let t="string"==typeof e?e:e.name;n.some((e=>e.name==t))||n.push("string"==typeof e?{name:t}:e)}};for(let n of t)if(n.hasResult()){let t=n.result.getMatch;if(!1===n.result.filter)for(let e of n.result.options)s(new Bu(e,n.source,t?t(e):[],1e9-i.length));else{let i=new Ku(e.sliceDoc(n.from,n.to));for(let e of n.result.options)if(i.match(e.label)){let r=e.displayLabel?t?t(e,i.matched):[]:i.matched;s(new Bu(e,n.source,r,i.score+(e.boost||0)))}}}if(n){let t=Object.create(null),e=0,s=(t,e)=>{var i,n;return(null!==(i=t.rank)&&void 0!==i?i:1e9)-(null!==(n=e.rank)&&void 0!==n?n:1e9)||(t.name<e.name?-1:1)};for(let i of n.sort(s))e-=1e5,t[i.name]=e;for(let e of i){let{section:i}=e.completion;i&&(e.score+=t["string"==typeof i?i:i.name])}}let r=[],o=null,a=e.facet(td).compareCompletions;for(let t of i.sort(((t,e)=>e.score-t.score||a(t.completion,e.completion)))){let e=t.completion;!o||o.label!=e.label||o.detail!=e.detail||null!=o.type&&null!=e.type&&o.type!=e.type||o.apply!=e.apply||o.boost!=e.boost?r.push(t):od(t.completion)>od(o)&&(r[r.length-1]=t),o=t.completion}return r}(t,e);if(!r.length)return n&&t.some((t=>1==t.state))?new ad(n.options,n.attrs,n.tooltip,n.timestamp,n.selected,!0):null;let o=e.facet(td).selectOnOpen?0:-1;if(n&&n.selected!=o&&-1!=n.selected){let t=n.options[n.selected].completion;for(let e=0;e<r.length;e++)if(r[e].completion==t){o=e;break}}return new ad(r,cd(i,o),{pos:t.reduce(((t,e)=>e.hasResult()?Math.min(t,e.from):t),1e8),create:vd,above:s.aboveCursor},n?n.timestamp:Date.now(),o,!1)}map(t){return new ad(this.options,this.attrs,Object.assign(Object.assign({},this.tooltip),{pos:t.mapPos(this.tooltip.pos)}),this.timestamp,this.selected,this.disabled)}}class ld{constructor(t,e,i){this.active=t,this.id=e,this.open=i}static start(){return new ld(fd,"cm-ac-"+Math.floor(2e6*Math.random()).toString(36),null)}update(t){let{state:e}=t,i=e.facet(td),n=(i.override||e.languageDataAt("autocomplete",Gu(e)).map(Hu)).map((e=>(this.active.find((t=>t.source==e))||new dd(e,this.active.some((t=>0!=t.state))?1:0)).update(t,i)));n.length==this.active.length&&n.every(((t,e)=>t==this.active[e]))&&(n=this.active);let s=this.open;s&&t.docChanged&&(s=s.map(t.changes)),t.selection||n.some((e=>e.hasResult()&&t.changes.touchesRange(e.from,e.to)))||!function(t,e){if(t==e)return!0;for(let i=0,n=0;;){for(;i<t.length&&!t[i].hasResult;)i++;for(;n<e.length&&!e[n].hasResult;)n++;let s=i==t.length,r=n==e.length;if(s||r)return s==r;if(t[i++].result!=e[n++].result)return!1}}(n,this.active)?s=ad.build(n,e,this.id,s,i):s&&s.disabled&&!n.some((t=>1==t.state))&&(s=null),!s&&n.every((t=>1!=t.state))&&n.some((t=>t.hasResult()))&&(n=n.map((t=>t.hasResult()?new dd(t.source,0):t)));for(let e of t.effects)e.is(gd)&&(s=s&&s.setSelected(e.value,this.id));return n==this.active&&s==this.open?this:new ld(n,this.id,s)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:hd}}const hd={"aria-autocomplete":"list"};function cd(t,e){let i={"aria-autocomplete":"list","aria-haspopup":"listbox","aria-controls":t};return e>-1&&(i["aria-activedescendant"]=t+"-"+e),i}const fd=[];function ud(t){return t.isUserEvent("input.type")?"input":t.isUserEvent("delete.backward")?"delete":null}class dd{constructor(t,e,i=-1){this.source=t,this.state=e,this.explicitPos=i}hasResult(){return!1}update(t,e){let i=ud(t),n=this;i?n=n.handleUserEvent(t,i,e):t.docChanged?n=n.handleChange(t):t.selection&&0!=n.state&&(n=new dd(n.source,0));for(let e of t.effects)if(e.is(Fu))n=new dd(n.source,1,e.value?Gu(t.state):-1);else if(e.is(Ju))n=new dd(n.source,0);else if(e.is(Od))for(let t of e.value)t.source==n.source&&(n=t);return n}handleUserEvent(t,e,i){return"delete"!=e&&i.activateOnTyping?new dd(this.source,1):this.map(t.changes)}handleChange(t){return t.changes.touchesRange(Gu(t.startState))?new dd(this.source,0):this.map(t.changes)}map(t){return t.empty||this.explicitPos<0?this:new dd(this.source,this.state,t.mapPos(this.explicitPos))}}class pd extends dd{constructor(t,e,i,n,s){super(t,2,e),this.result=i,this.from=n,this.to=s}hasResult(){return!0}handleUserEvent(t,e,i){var n;let s=t.changes.mapPos(this.from),r=t.changes.mapPos(this.to,1),o=Gu(t.state);if((this.explicitPos<0?o<=s:o<this.from)||o>r||"delete"==e&&Gu(t.startState)==this.from)return new dd(this.source,"input"==e&&i.activateOnTyping?1:0);let a,l=this.explicitPos<0?-1:t.changes.mapPos(this.explicitPos);return function(t,e,i,n){if(!t)return!1;let s=e.sliceDoc(i,n);return"function"==typeof t?t(s,i,n,e):Lu(t,!0).test(s)}(this.result.validFor,t.state,s,r)?new pd(this.source,l,this.result,s,r):this.result.update&&(a=this.result.update(this.result,s,r,new Vu(t.state,o,l>=0)))?new pd(this.source,l,a,a.from,null!==(n=a.to)&&void 0!==n?n:Gu(t.state)):new dd(this.source,1,l)}handleChange(t){return t.changes.touchesRange(this.from,this.to)?new dd(this.source,0):this.map(t.changes)}map(t){return t.empty?this:new pd(this.source,this.explicitPos<0?-1:t.mapPos(this.explicitPos),this.result,t.mapPos(this.from),t.mapPos(this.to,1))}}const Od=dt.define({map:(t,e)=>t.map((t=>t.map(e)))}),gd=dt.define(),md=z.define({create:()=>ld.start(),update:(t,e)=>t.update(e),provide:t=>[no.from(t,(t=>t.tooltip)),Gs.contentAttributes.from(t,(t=>t.attrs))]});function wd(t,e){const i=e.completion.apply||e.completion.label;let n=t.state.field(md).active.find((t=>t.source==e.source));return n instanceof pd&&("string"==typeof i?t.dispatch(Object.assign(Object.assign({},function(t,e,i,n){let{main:s}=t.selection,r=i-s.from,o=n-s.from;return Object.assign(Object.assign({},t.changeByRange((a=>a!=s&&i!=n&&t.sliceDoc(a.from+r,a.from+o)!=t.sliceDoc(i,n)?{range:a}:{changes:{from:a.from+r,to:n==s.from?a.to:a.from+o,insert:e},range:Y.cursor(a.from+r+e.length)}))),{scrollIntoView:!0,userEvent:"input.complete"})}(t.state,i,n.from,n.to)),{annotations:Nu.of(e.completion)})):i(t,e.completion,n.from,n.to),!0)}const vd=rd(md,wd);function bd(t,e="option"){return i=>{let n=i.state.field(md,!1);if(!n||!n.open||n.open.disabled||Date.now()-n.open.timestamp<i.state.facet(td).interactionDelay)return!1;let s,r=1;"page"==e&&(s=co(i,n.open.tooltip))&&(r=Math.max(2,Math.floor(s.dom.offsetHeight/s.dom.querySelector("li").offsetHeight)-1));let{length:o}=n.open.options,a=n.open.selected>-1?n.open.selected+r*(t?1:-1):t?0:o-1;return a<0?a="page"==e?0:o-1:a>=o&&(a="page"==e?o-1:0),i.dispatch({effects:gd.of(a)}),!0}}class yd{constructor(t,e){this.active=t,this.context=e,this.time=Date.now(),this.updates=[],this.done=void 0}}const Sd=Ni.fromClass(class{constructor(t){this.view=t,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.pendingStart=!1,this.composing=0;for(let e of t.state.field(md).active)1==e.state&&this.startQuery(e)}update(t){let e=t.state.field(md);if(!t.selectionSet&&!t.docChanged&&t.startState.field(md)==e)return;let i=t.transactions.some((t=>(t.selection||t.docChanged)&&!ud(t)));for(let e=0;e<this.running.length;e++){let n=this.running[e];if(i||n.updates.length+t.transactions.length>50&&Date.now()-n.time>1e3){for(let t of n.context.abortListeners)try{t()}catch(t){zi(this.view.state,t)}n.context.abortListeners=null,this.running.splice(e--,1)}else n.updates.push(...t.transactions)}this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),t.transactions.some((t=>t.effects.some((t=>t.is(Fu)))))&&(this.pendingStart=!0);let n=this.pendingStart?50:t.state.facet(td).activateOnTypingDelay;if(this.debounceUpdate=e.active.some((t=>1==t.state&&!this.running.some((e=>e.active.source==t.source))))?setTimeout((()=>this.startUpdate()),n):-1,0!=this.composing)for(let e of t.transactions)"input"==ud(e)?this.composing=2:2==this.composing&&e.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1,this.pendingStart=!1;let{state:t}=this.view,e=t.field(md);for(let t of e.active)1!=t.state||this.running.some((e=>e.active.source==t.source))||this.startQuery(t)}startQuery(t){let{state:e}=this.view,i=Gu(e),n=new Vu(e,i,t.explicitPos==i),s=new yd(t,n);this.running.push(s),Promise.resolve(t.source(n)).then((t=>{s.context.aborted||(s.done=t||null,this.scheduleAccept())}),(t=>{this.view.dispatch({effects:Ju.of(null)}),zi(this.view.state,t)}))}scheduleAccept(){this.running.every((t=>void 0!==t.done))?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout((()=>this.accept()),this.view.state.facet(td).updateSyncTime))}accept(){var t;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let e=[],i=this.view.state.facet(td);for(let n=0;n<this.running.length;n++){let s=this.running[n];if(void 0===s.done)continue;if(this.running.splice(n--,1),s.done){let n=new pd(s.active.source,s.active.explicitPos,s.done,s.done.from,null!==(t=s.done.to)&&void 0!==t?t:Gu(s.updates.length?s.updates[0].startState:this.view.state));for(let t of s.updates)n=n.update(t,i);if(n.hasResult()){e.push(n);continue}}let r=this.view.state.field(md).active.find((t=>t.source==s.active.source));if(r&&1==r.state)if(null==s.done){let t=new dd(s.active.source,0);for(let e of s.updates)t=t.update(e,i);1!=t.state&&e.push(t)}else this.startQuery(r)}e.length&&this.view.dispatch({effects:Od.of(e)})}},{eventHandlers:{blur(t){let e=this.view.state.field(md,!1);if(e&&e.tooltip&&this.view.state.facet(td).closeOnBlur){let i=e.open&&co(this.view,e.open.tooltip);i&&i.dom.contains(t.relatedTarget)||setTimeout((()=>this.view.dispatch({effects:Ju.of(null)})),10)}},compositionstart(){this.composing=1},compositionend(){3==this.composing&&setTimeout((()=>this.view.dispatch({effects:Fu.of(!1)})),20),this.composing=0}}}),xd=Gs.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",height:"100%",listStyle:"none",margin:0,padding:0,"& > li, & > completion-section":{padding:"1px 3px",lineHeight:1.2},"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer"},"& > completion-section":{display:"list-item",borderBottom:"1px solid silver",paddingLeft:"0.5em",opacity:.7}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#777"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#444"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"···"',opacity:.5,display:"block",textAlign:"center"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"400px",boxSizing:"border-box"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"30px"},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"30px"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6",boxSizing:"content-box"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'ƒ'"}},".cm-completionIcon-class":{"&:after":{content:"'○'"}},".cm-completionIcon-interface":{"&:after":{content:"'◌'"}},".cm-completionIcon-variable":{"&:after":{content:"'𝑥'"}},".cm-completionIcon-constant":{"&:after":{content:"'𝐶'"}},".cm-completionIcon-type":{"&:after":{content:"'𝑡'"}},".cm-completionIcon-enum":{"&:after":{content:"'∪'"}},".cm-completionIcon-property":{"&:after":{content:"'□'"}},".cm-completionIcon-keyword":{"&:after":{content:"'🔑︎'"}},".cm-completionIcon-namespace":{"&:after":{content:"'▢'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}});class kd{constructor(t,e,i,n){this.field=t,this.line=e,this.from=i,this.to=n}}class Qd{constructor(t,e,i){this.field=t,this.from=e,this.to=i}map(t){let e=t.mapPos(this.from,-1,k.TrackDel),i=t.mapPos(this.to,1,k.TrackDel);return null==e||null==i?null:new Qd(this.field,e,i)}}class $d{constructor(t,e){this.lines=t,this.fieldPositions=e}instantiate(t,e){let i=[],n=[e],s=t.doc.lineAt(e),r=/^\s*/.exec(s.text)[0];for(let s of this.lines){if(i.length){let i=r,o=/^\t*/.exec(s)[0].length;for(let e=0;e<o;e++)i+=t.facet(kl);n.push(e+i.length-o),s=i+s.slice(o)}i.push(s),e+=s.length+1}let o=this.fieldPositions.map((t=>new Qd(t.field,n[t.line]+t.from,n[t.line]+t.to)));return{text:i,ranges:o}}static parse(t){let e,i=[],n=[],s=[];for(let r of t.split(/\r\n?|\n/)){for(;e=/[#$]\{(?:(\d+)(?::([^}]*))?|([^}]*))\}/.exec(r);){let t=e[1]?+e[1]:null,o=e[2]||e[3]||"",a=-1;for(let e=0;e<i.length;e++)(null!=t?i[e].seq==t:o&&i[e].name==o)&&(a=e);if(a<0){let e=0;for(;e<i.length&&(null==t||null!=i[e].seq&&i[e].seq<t);)e++;i.splice(e,0,{seq:t,name:o}),a=e;for(let t of s)t.field>=a&&t.field++}s.push(new kd(a,n.length,e.index,e.index+o.length)),r=r.slice(0,e.index)+o+r.slice(e.index+e[0].length)}for(let t;t=/\\([{}])/.exec(r);){r=r.slice(0,t.index)+t[1]+r.slice(t.index+t[0].length);for(let e of s)e.line==n.length&&e.from>t.index&&(e.from--,e.to--)}n.push(r)}return new $d(n,s)}}let Pd=si.widget({widget:new class extends ii{toDOM(){let t=document.createElement("span");return t.className="cm-snippetFieldPosition",t}ignoreEvent(){return!1}}}),Zd=si.mark({class:"cm-snippetField"});class Cd{constructor(t,e){this.ranges=t,this.active=e,this.deco=si.set(t.map((t=>(t.from==t.to?Pd:Zd).range(t.from,t.to))))}map(t){let e=[];for(let i of this.ranges){let n=i.map(t);if(!n)return null;e.push(n)}return new Cd(e,this.active)}selectionInsideField(t){return t.ranges.every((t=>this.ranges.some((e=>e.field==this.active&&e.from<=t.from&&e.to>=t.to))))}}const Td=dt.define({map:(t,e)=>t&&t.map(e)}),Ad=dt.define(),Rd=z.define({create:()=>null,update(t,e){for(let i of e.effects){if(i.is(Td))return i.value;if(i.is(Ad)&&t)return new Cd(t.ranges,i.value)}return t&&e.docChanged&&(t=t.map(e.changes)),t&&e.selection&&!t.selectionInsideField(e.selection)&&(t=null),t},provide:t=>Gs.decorations.from(t,(t=>t?t.deco:si.none))});function Xd(t,e){return Y.create(t.filter((t=>t.field==e)).map((t=>Y.range(t.from,t.to))))}function Yd(t){let i=$d.parse(t);return(t,n,s,r)=>{let{text:o,ranges:a}=i.instantiate(t.state,s),l={changes:{from:s,to:r,insert:e.of(o)},scrollIntoView:!0,annotations:n?[Nu.of(n),pt.userEvent.of("input.complete")]:void 0};if(a.length&&(l.selection=Xd(a,0)),a.some((t=>t.field>0))){let e=new Cd(a,0),i=l.effects=[Td.of(e)];void 0===t.state.field(Rd,!1)&&i.push(dt.appendConfig.of([Rd,Dd,qd,xd]))}t.dispatch(t.state.update(l))}}function Wd(t){return({state:e,dispatch:i})=>{let n=e.field(Rd,!1);if(!n||t<0&&0==n.active)return!1;let s=n.active+t,r=t>0&&!n.ranges.some((e=>e.field==s+t));return i(e.update({selection:Xd(n.ranges,s),effects:Td.of(r?null:new Cd(n.ranges,s)),scrollIntoView:!0})),!0}}const Md=[{key:"Tab",run:Wd(1),shift:Wd(-1)},{key:"Escape",run:({state:t,dispatch:e})=>!!t.field(Rd,!1)&&(e(t.update({effects:Td.of(null)})),!0)}],jd=j.define({combine:t=>t.length?t[0]:Md}),Dd=H.highest(tr.compute([jd],(t=>t.facet(jd))));function Ed(t,e){return Object.assign(Object.assign({},e),{apply:Yd(t)})}const qd=Gs.domEventHandlers({mousedown(t,e){let i,n=e.state.field(Rd,!1);if(!n||null==(i=e.posAtCoords({x:t.clientX,y:t.clientY})))return!1;let s=n.ranges.find((t=>t.from<=i&&t.to>=i));return!(!s||s.field==n.active)&&(e.dispatch({selection:Xd(n.ranges,s.field),effects:Td.of(n.ranges.some((t=>t.field>s.field))?new Cd(n.ranges,s.field):null),scrollIntoView:!0}),!0)}}),_d={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},Vd=dt.define({map(t,e){let i=e.mapPos(t,-1,k.TrackAfter);return null==i?void 0:i}}),Id=new class extends Pt{};Id.startSide=1,Id.endSide=-1;const zd=z.define({create:()=>At.empty,update(t,e){if(t=t.map(e.changes),e.selection){let i=e.state.doc.lineAt(e.selection.main.head);t=t.update({filter:t=>t>=i.from&&t<=i.to})}for(let i of e.effects)i.is(Vd)&&(t=t.update({add:[Id.range(i.value,i.value+1)]}));return t}});const Bd="()[]{}<>";function Gd(t){for(let e=0;e<Bd.length;e+=2)if(Bd.charCodeAt(e)==t)return Bd.charAt(e+1);return y(t<128?t:t+1)}function Ld(t,e){return t.languageDataAt("closeBrackets",e)[0]||_d}const Nd="object"==typeof navigator&&/Android\b/.test(navigator.userAgent),Ud=Gs.inputHandler.of(((t,e,i,n)=>{if((Nd?t.composing:t.compositionStarted)||t.state.readOnly)return!1;let s=t.state.selection.main;if(n.length>2||2==n.length&&1==S(b(n,0))||e!=s.from||i!=s.to)return!1;let r=function(t,e){let i=Ld(t,t.selection.main.head),n=i.brackets||_d.brackets;for(let s of n){let r=Gd(b(s,0));if(e==s)return r==s?ep(t,s,n.indexOf(s+s+s)>-1,i):Kd(t,s,r,i.before||_d.before);if(e==r&&Fd(t,t.selection.main.from))return tp(t,s,r)}return null}(t.state,n);return!!r&&(t.dispatch(r),!0)})),Hd=[{key:"Backspace",run:({state:t,dispatch:e})=>{if(t.readOnly)return!1;let i=Ld(t,t.selection.main.head).brackets||_d.brackets,n=null,s=t.changeByRange((e=>{if(e.empty){let n=function(t,e){let i=t.sliceString(e-2,e);return S(b(i,0))==i.length?i:i.slice(1)}(t.doc,e.head);for(let s of i)if(s==n&&Jd(t.doc,e.head)==Gd(b(s,0)))return{changes:{from:e.head-s.length,to:e.head+s.length},range:Y.cursor(e.head-s.length)}}return{range:n=e}}));return n||e(t.update(s,{scrollIntoView:!0,userEvent:"delete.backward"})),!n}}];function Fd(t,e){let i=!1;return t.field(zd).between(0,t.doc.length,(t=>{t==e&&(i=!0)})),i}function Jd(t,e){let i=t.sliceString(e,e+2);return i.slice(0,S(b(i,0)))}function Kd(t,e,i,n){let s=null,r=t.changeByRange((r=>{if(!r.empty)return{changes:[{insert:e,from:r.from},{insert:i,from:r.to}],effects:Vd.of(r.to+e.length),range:Y.range(r.anchor+e.length,r.head+e.length)};let o=Jd(t.doc,r.head);return!o||/\s/.test(o)||n.indexOf(o)>-1?{changes:{insert:e+i,from:r.head},effects:Vd.of(r.head+e.length),range:Y.cursor(r.head+e.length)}:{range:s=r}}));return s?null:t.update(r,{scrollIntoView:!0,userEvent:"input.type"})}function tp(t,e,i){let n=null,s=t.changeByRange((e=>e.empty&&Jd(t.doc,e.head)==i?{changes:{from:e.head,to:e.head+i.length,insert:i},range:Y.cursor(e.head+i.length)}:n={range:e}));return n?null:t.update(s,{scrollIntoView:!0,userEvent:"input.type"})}function ep(t,e,i,n){let s=n.stringPrefixes||_d.stringPrefixes,r=null,o=t.changeByRange((n=>{if(!n.empty)return{changes:[{insert:e,from:n.from},{insert:e,from:n.to}],effects:Vd.of(n.to+e.length),range:Y.range(n.anchor+e.length,n.head+e.length)};let o,a=n.head,l=Jd(t.doc,a);if(l==e){if(ip(t,a))return{changes:{insert:e+e,from:a},effects:Vd.of(a+e.length),range:Y.cursor(a+e.length)};if(Fd(t,a)){let n=i&&t.sliceDoc(a,a+3*e.length)==e+e+e?e+e+e:e;return{changes:{from:a,to:a+n.length,insert:n},range:Y.cursor(a+n.length)}}}else{if(i&&t.sliceDoc(a-2*e.length,a)==e+e&&(o=np(t,a-2*e.length,s))>-1&&ip(t,o))return{changes:{insert:e+e+e+e,from:a},effects:Vd.of(a+e.length),range:Y.cursor(a+e.length)};if(t.charCategorizer(a)(l)!=yt.Word&&np(t,a,s)>-1&&!function(t,e,i,n){let s=cl(t).resolveInner(e,-1),r=n.reduce(((t,e)=>Math.max(t,e.length)),0);for(let o=0;o<5;o++){let o=t.sliceDoc(s.from,Math.min(s.to,s.from+i.length+r)),a=o.indexOf(i);if(!a||a>-1&&n.indexOf(o.slice(0,a))>-1){let e=s.firstChild;for(;e&&e.from==s.from&&e.to-e.from>i.length+a;){if(t.sliceDoc(e.to-i.length,e.to)==i)return!1;e=e.firstChild}return!0}let l=s.to==e&&s.parent;if(!l)break;s=l}return!1}(t,a,e,s))return{changes:{insert:e+e,from:a},effects:Vd.of(a+e.length),range:Y.cursor(a+e.length)}}return{range:r=n}}));return r?null:t.update(o,{scrollIntoView:!0,userEvent:"input.type"})}function ip(t,e){let i=cl(t).resolveInner(e+1);return i.parent&&i.from==e}function np(t,e,i){let n=t.charCategorizer(e);if(n(t.sliceDoc(e-1,e))!=yt.Word)return e;for(let s of i){let i=e-s.length;if(t.sliceDoc(i,e)==s&&n(t.sliceDoc(i-1,i))!=yt.Word)return i}return-1}function sp(t={}){return[md,td.of(t),Sd,op,xd]}const rp=[{key:"Ctrl-Space",run:t=>!!t.state.field(md,!1)&&(t.dispatch({effects:Fu.of(!0)}),!0)},{key:"Escape",run:t=>{let e=t.state.field(md,!1);return!(!e||!e.active.some((t=>0!=t.state)))&&(t.dispatch({effects:Ju.of(null)}),!0)}},{key:"ArrowDown",run:bd(!0)},{key:"ArrowUp",run:bd(!1)},{key:"PageDown",run:bd(!0,"page")},{key:"PageUp",run:bd(!1,"page")},{key:"Enter",run:t=>{let e=t.state.field(md,!1);return!(t.state.readOnly||!e||!e.open||e.open.selected<0||e.open.disabled||Date.now()-e.open.timestamp<t.state.facet(td).interactionDelay)&&wd(t,e.open.options[e.open.selected])}}],op=H.highest(tr.computeN([td],(t=>t.facet(td).defaultKeymap?[rp]:[])));class ap{constructor(t,e,i){this.from=t,this.to=e,this.diagnostic=i}}class lp{constructor(t,e,i){this.diagnostics=t,this.panel=e,this.selected=i}static init(t,e,i){let n=t,s=i.facet(vp).markerFilter;s&&(n=s(n,i));let r=si.set(n.map((t=>t.from==t.to||t.from==t.to-1&&i.doc.lineAt(t.from).to==t.from?si.widget({widget:new Sp(t),diagnostic:t}).range(t.from):si.mark({attributes:{class:"cm-lintRange cm-lintRange-"+t.severity+(t.markClass?" "+t.markClass:"")},diagnostic:t,inclusive:!0}).range(t.from,t.to))),!0);return new lp(r,e,hp(r))}}function hp(t,e=null,i=0){let n=null;return t.between(i,1e9,((t,i,{spec:s})=>{if(!e||s.diagnostic==e)return n=new ap(t,i,s.diagnostic),!1})),n}const cp=dt.define(),fp=dt.define(),up=dt.define(),dp=z.define({create:()=>new lp(si.none,null,null),update(t,e){if(e.docChanged){let i=t.diagnostics.map(e.changes),n=null;if(t.selected){let s=e.changes.mapPos(t.selected.from,1);n=hp(i,t.selected.diagnostic,s)||hp(i,null,s)}t=new lp(i,t.panel,n)}for(let i of e.effects)i.is(cp)?t=lp.init(i.value,t.panel,e.state):i.is(fp)?t=new lp(t.diagnostics,i.value?kp.open:null,t.selected):i.is(up)&&(t=new lp(t.diagnostics,t.panel,i.value));return t},provide:t=>[vo.from(t,(t=>t.panel)),Gs.decorations.from(t,(t=>t.diagnostics))]}),pp=si.mark({class:"cm-lintRange cm-lintRange-active",inclusive:!0});function Op(t,e,i){let{diagnostics:n}=t.state.field(dp),s=[],r=2e8,o=0;n.between(e-(i<0?1:0),e+(i>0?1:0),((t,n,{spec:a})=>{e>=t&&e<=n&&(t==n||(e>t||i>0)&&(e<n||i<0))&&(s.push(a.diagnostic),r=Math.min(t,r),o=Math.max(n,o))}));let a=t.state.facet(vp).tooltipFilter;return a&&(s=a(s,t.state)),s.length?{pos:r,end:o,above:t.state.doc.lineAt(r).to<o,create:()=>({dom:gp(t,s)})}:null}function gp(t,e){return jf("ul",{class:"cm-tooltip-lint"},e.map((e=>yp(t,e,!1))))}const mp=t=>{let e=t.state.field(dp,!1);return!(!e||!e.panel)&&(t.dispatch({effects:fp.of(!1)}),!0)},wp=[{key:"Mod-Shift-m",run:t=>{let e=t.state.field(dp,!1);var i,n;e&&e.panel||t.dispatch({effects:(i=t.state,n=[fp.of(!0)],i.field(dp,!1)?n:n.concat(dt.appendConfig.of(Pp)))});let s=Oo(t,kp.open);return s&&s.dom.querySelector(".cm-panel-lint ul").focus(),!0},preventDefault:!0},{key:"F8",run:t=>{let e=t.state.field(dp,!1);if(!e)return!1;let i=t.state.selection.main,n=e.diagnostics.iter(i.to+1);return!(!n.value&&(n=e.diagnostics.iter(0),!n.value||n.from==i.from&&n.to==i.to))&&(t.dispatch({selection:{anchor:n.from,head:n.to},scrollIntoView:!0}),!0)}}],vp=j.define({combine:t=>Object.assign({sources:t.map((t=>t.source)).filter((t=>null!=t))},$t(t.map((t=>t.config)),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null},{needsRefresh:(t,e)=>t?e?i=>t(i)||e(i):t:e}))});function bp(t){let e=[];if(t)t:for(let{name:i}of t){for(let t=0;t<i.length;t++){let n=i[t];if(/[a-zA-Z]/.test(n)&&!e.some((t=>t.toLowerCase()==n.toLowerCase()))){e.push(n);continue t}}e.push("")}return e}function yp(t,e,i){var n;let s=i?bp(e.actions):[];return jf("li",{class:"cm-diagnostic cm-diagnostic-"+e.severity},jf("span",{class:"cm-diagnosticText"},e.renderMessage?e.renderMessage():e.message),null===(n=e.actions)||void 0===n?void 0:n.map(((i,n)=>{let r=!1,o=n=>{if(n.preventDefault(),r)return;r=!0;let s=hp(t.state.field(dp).diagnostics,e);s&&i.apply(t,s.from,s.to)},{name:a}=i,l=s[n]?a.indexOf(s[n]):-1,h=l<0?a:[a.slice(0,l),jf("u",a.slice(l,l+1)),a.slice(l+1)];return jf("button",{type:"button",class:"cm-diagnosticAction",onclick:o,onmousedown:o,"aria-label":` Action: ${a}${l<0?"":` (access key "${s[n]})"`}.`},h)})),e.source&&jf("div",{class:"cm-diagnosticSource"},e.source))}class Sp extends ii{constructor(t){super(),this.diagnostic=t}eq(t){return t.diagnostic==this.diagnostic}toDOM(){return jf("span",{class:"cm-lintPoint cm-lintPoint-"+this.diagnostic.severity})}}class xp{constructor(t,e){this.diagnostic=e,this.id="item_"+Math.floor(4294967295*Math.random()).toString(16),this.dom=yp(t,e,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class kp{constructor(t){this.view=t,this.items=[];this.list=jf("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:e=>{if(27==e.keyCode)mp(this.view),this.view.focus();else if(38==e.keyCode||33==e.keyCode)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(40==e.keyCode||34==e.keyCode)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(36==e.keyCode)this.moveSelection(0);else if(35==e.keyCode)this.moveSelection(this.items.length-1);else if(13==e.keyCode)this.view.focus();else{if(!(e.keyCode>=65&&e.keyCode<=90&&this.selectedIndex>=0))return;{let{diagnostic:i}=this.items[this.selectedIndex],n=bp(i.actions);for(let s=0;s<n.length;s++)if(n[s].toUpperCase().charCodeAt(0)==e.keyCode){let e=hp(this.view.state.field(dp).diagnostics,i);e&&i.actions[s].apply(t,e.from,e.to)}}}e.preventDefault()},onclick:t=>{for(let e=0;e<this.items.length;e++)this.items[e].dom.contains(t.target)&&this.moveSelection(e)}}),this.dom=jf("div",{class:"cm-panel-lint"},this.list,jf("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>mp(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(dp).selected;if(!t)return-1;for(let e=0;e<this.items.length;e++)if(this.items[e].diagnostic==t.diagnostic)return e;return-1}update(){let{diagnostics:t,selected:e}=this.view.state.field(dp),i=0,n=!1,s=null;for(t.between(0,this.view.state.doc.length,((t,r,{spec:o})=>{let a,l=-1;for(let t=i;t<this.items.length;t++)if(this.items[t].diagnostic==o.diagnostic){l=t;break}l<0?(a=new xp(this.view,o.diagnostic),this.items.splice(i,0,a),n=!0):(a=this.items[l],l>i&&(this.items.splice(i,l-i),n=!0)),e&&a.diagnostic==e.diagnostic?a.dom.hasAttribute("aria-selected")||(a.dom.setAttribute("aria-selected","true"),s=a):a.dom.hasAttribute("aria-selected")&&a.dom.removeAttribute("aria-selected"),i++}));i<this.items.length&&!(1==this.items.length&&this.items[0].diagnostic.from<0);)n=!0,this.items.pop();0==this.items.length&&(this.items.push(new xp(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),n=!0),s?(this.list.setAttribute("aria-activedescendant",s.id),this.view.requestMeasure({key:this,read:()=>({sel:s.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:t,panel:e})=>{let i=e.height/this.list.offsetHeight;t.top<e.top?this.list.scrollTop-=(e.top-t.top)/i:t.bottom>e.bottom&&(this.list.scrollTop+=(t.bottom-e.bottom)/i)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),n&&this.sync()}sync(){let t=this.list.firstChild;function e(){let e=t;t=e.nextSibling,e.remove()}for(let i of this.items)if(i.dom.parentNode==this.list){for(;t!=i.dom;)e();t=i.dom.nextSibling}else this.list.insertBefore(i.dom,t);for(;t;)e()}moveSelection(t){if(this.selectedIndex<0)return;let e=hp(this.view.state.field(dp).diagnostics,this.items[t].diagnostic);e&&this.view.dispatch({selection:{anchor:e.from,head:e.to},scrollIntoView:!0,effects:up.of(e)})}static open(t){return new kp(t)}}function Qp(t){return function(t,e='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${e}>${encodeURIComponent(t)}</svg>')`}(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${t}" fill="none" stroke-width=".7"/>`,'width="6" height="3"')}const $p=Gs.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:Qp("#d11")},".cm-lintRange-warning":{backgroundImage:Qp("orange")},".cm-lintRange-info":{backgroundImage:Qp("#999")},".cm-lintRange-hint":{backgroundImage:Qp("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}}),Pp=[dp,Gs.decorations.compute([dp],(t=>{let{selected:e,panel:i}=t.field(dp);return e&&i&&e.from!=e.to?si.set([pp.range(e.from,e.to)]):si.none})),ho(Op,{hideOn:function(t,e){let i=t.startState.doc.lineAt(e.pos);return!(!t.effects.some((t=>t.is(cp)))&&!t.changes.touchesRange(i.from,i.to))}}),$p],Zp=(()=>[Do(),Vo(),Xr(),kc(),ph(),Or(),Qr(),Qt.allowMultipleSelections.of(!0),El(),bh(xh,{fallback:!0}),Xh(),[Ud,zd],sp(),Br(),Nr(),Dr(),tu(),tr.of([...Hd,...Mf,...Yu,..._c,...rh,...rp,...wp])])(),Cp=(()=>[Xr(),kc(),Or(),bh(xh,{fallback:!0}),tr.of([...Mf,..._c])])();var Tp=Object.freeze({__proto__:null,EditorView:Gs,basicSetup:Zp,minimalSetup:Cp});class Ap{constructor(t,e,i,n,s,r,o,a,l,h=0,c){this.p=t,this.stack=e,this.state=i,this.reducePos=n,this.pos=s,this.score=r,this.buffer=o,this.bufferBase=a,this.curContext=l,this.lookAhead=h,this.parent=c}toString(){return`[${this.stack.filter(((t,e)=>e%3==0)).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(t,e,i=0){let n=t.parser.context;return new Ap(t,[],e,i,i,0,[],0,n?new Rp(n,n.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(t,e){this.stack.push(this.state,e,this.bufferBase+this.buffer.length),this.state=t}reduce(t){var e;let i=t>>19,n=65535&t,{parser:s}=this.p,r=s.dynamicPrecedence(n);if(r&&(this.score+=r),0==i)return this.pushState(s.getGoto(this.state,n,!0),this.reducePos),n<s.minRepeatTerm&&this.storeNode(n,this.reducePos,this.reducePos,4,!0),void this.reduceContext(n,this.reducePos);let o=this.stack.length-3*(i-1)-(262144&t?6:0),a=o?this.stack[o-2]:this.p.ranges[0].from,l=this.reducePos-a;l>=2e3&&!(null===(e=this.p.parser.nodeSet.types[n])||void 0===e?void 0:e.isAnonymous)&&(a==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=l):this.p.lastBigReductionSize<l&&(this.p.bigReductionCount=1,this.p.lastBigReductionStart=a,this.p.lastBigReductionSize=l));let h=o?this.stack[o-1]:0,c=this.bufferBase+this.buffer.length-h;if(n<s.minRepeatTerm||131072&t){let t=s.stateFlag(this.state,1)?this.pos:this.reducePos;this.storeNode(n,a,t,c+4,!0)}if(262144&t)this.state=this.stack[o];else{let t=this.stack[o-3];this.state=s.getGoto(t,n,!0)}for(;this.stack.length>o;)this.stack.pop();this.reduceContext(n,a)}storeNode(t,e,i,n=4,s=!1){if(0==t&&(!this.stack.length||this.stack[this.stack.length-1]<this.buffer.length+this.bufferBase)){let t=this,n=this.buffer.length;if(0==n&&t.parent&&(n=t.bufferBase-t.parent.bufferBase,t=t.parent),n>0&&0==t.buffer[n-4]&&t.buffer[n-1]>-1){if(e==i)return;if(t.buffer[n-2]>=e)return void(t.buffer[n-2]=i)}}if(s&&this.pos!=i){let s=this.buffer.length;if(s>0&&0!=this.buffer[s-4])for(;s>0&&this.buffer[s-2]>i;)this.buffer[s]=this.buffer[s-4],this.buffer[s+1]=this.buffer[s-3],this.buffer[s+2]=this.buffer[s-2],this.buffer[s+3]=this.buffer[s-1],s-=4,n>4&&(n-=4);this.buffer[s]=t,this.buffer[s+1]=e,this.buffer[s+2]=i,this.buffer[s+3]=n}else this.buffer.push(t,e,i,n)}shift(t,e,i,n){if(131072&t)this.pushState(65535&t,this.pos);else if(0==(262144&t)){let s=t,{parser:r}=this.p;(n>this.pos||e<=r.maxNode)&&(this.pos=n,r.stateFlag(s,1)||(this.reducePos=n)),this.pushState(s,i),this.shiftContext(e,i),e<=r.maxNode&&this.buffer.push(e,i,n,4)}else this.pos=n,this.shiftContext(e,i),e<=this.p.parser.maxNode&&this.buffer.push(e,i,n,4)}apply(t,e,i,n){65536&t?this.reduce(t):this.shift(t,e,i,n)}useNode(t,e){let i=this.p.reused.length-1;(i<0||this.p.reused[i]!=t)&&(this.p.reused.push(t),i++);let n=this.pos;this.reducePos=this.pos=n+t.length,this.pushState(e,n),this.buffer.push(i,n,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,t,this,this.p.stream.reset(this.pos-t.length)))}split(){let t=this,e=t.buffer.length;for(;e>0&&t.buffer[e-2]>t.reducePos;)e-=4;let i=t.buffer.slice(e),n=t.bufferBase+e;for(;t&&n==t.bufferBase;)t=t.parent;return new Ap(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,i,n,this.curContext,this.lookAhead,t)}recoverByDelete(t,e){let i=t<=this.p.parser.maxNode;i&&this.storeNode(t,this.pos,e,4),this.storeNode(0,this.pos,e,i?8:4),this.pos=this.reducePos=e,this.score-=190}canShift(t){for(let e=new Xp(this);;){let i=this.p.parser.stateSlot(e.state,4)||this.p.parser.hasAction(e.state,t);if(0==i)return!1;if(0==(65536&i))return!0;e.reduce(i)}}recoverByInsert(t){if(this.stack.length>=300)return[];let e=this.p.parser.nextStates(this.state);if(e.length>8||this.stack.length>=120){let i=[];for(let n,s=0;s<e.length;s+=2)(n=e[s+1])!=this.state&&this.p.parser.hasAction(n,t)&&i.push(e[s],n);if(this.stack.length<120)for(let t=0;i.length<8&&t<e.length;t+=2){let n=e[t+1];i.some(((t,e)=>1&e&&t==n))||i.push(e[t],n)}e=i}let i=[];for(let t=0;t<e.length&&i.length<4;t+=2){let n=e[t+1];if(n==this.state)continue;let s=this.split();s.pushState(n,this.pos),s.storeNode(0,s.pos,s.pos,4,!0),s.shiftContext(e[t],this.pos),s.reducePos=this.pos,s.score-=200,i.push(s)}return i}forceReduce(){let{parser:t}=this.p,e=t.stateSlot(this.state,5);if(0==(65536&e))return!1;if(!t.validAction(this.state,e)){let i=e>>19,n=65535&e,s=this.stack.length-3*i;if(s<0||t.getGoto(this.stack[s],n,!1)<0){let t=this.findForcedReduction();if(null==t)return!1;e=t}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(e),!0}findForcedReduction(){let{parser:t}=this.p,e=[],i=(n,s)=>{if(!e.includes(n))return e.push(n),t.allActions(n,(e=>{if(393216&e);else if(65536&e){let i=(e>>19)-s;if(i>1){let n=65535&e,s=this.stack.length-3*i;if(s>=0&&t.getGoto(this.stack[s],n,!1)>=0)return i<<19|65536|n}}else{let t=i(e,s+1);if(null!=t)return t}}))};return i(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(3!=this.stack.length)return!1;let{parser:t}=this.p;return 65535==t.data[t.stateSlot(this.state,1)]&&!t.stateSlot(this.state,4)}restart(){this.storeNode(0,this.pos,this.pos,4,!0),this.state=this.stack[0],this.stack.length=0}sameState(t){if(this.state!=t.state||this.stack.length!=t.stack.length)return!1;for(let e=0;e<this.stack.length;e+=3)if(this.stack[e]!=t.stack[e])return!1;return!0}get parser(){return this.p.parser}dialectEnabled(t){return this.p.parser.dialect.flags[t]}shiftContext(t,e){this.curContext&&this.updateContext(this.curContext.tracker.shift(this.curContext.context,t,this,this.p.stream.reset(e)))}reduceContext(t,e){this.curContext&&this.updateContext(this.curContext.tracker.reduce(this.curContext.context,t,this,this.p.stream.reset(e)))}emitContext(){let t=this.buffer.length-1;(t<0||-3!=this.buffer[t])&&this.buffer.push(this.curContext.hash,this.pos,this.pos,-3)}emitLookAhead(){let t=this.buffer.length-1;(t<0||-4!=this.buffer[t])&&this.buffer.push(this.lookAhead,this.pos,this.pos,-4)}updateContext(t){if(t!=this.curContext.context){let e=new Rp(this.curContext.tracker,t);e.hash!=this.curContext.hash&&this.emitContext(),this.curContext=e}}setLookAhead(t){t>this.lookAhead&&(this.emitLookAhead(),this.lookAhead=t)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}}class Rp{constructor(t,e){this.tracker=t,this.context=e,this.hash=t.strict?t.hash(e):0}}class Xp{constructor(t){this.start=t,this.state=t.state,this.stack=t.stack,this.base=this.stack.length}reduce(t){let e=65535&t,i=t>>19;0==i?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=3*(i-1);let n=this.start.p.parser.getGoto(this.stack[this.base-3],e,!0);this.state=n}}class Yp{constructor(t,e,i){this.stack=t,this.pos=e,this.index=i,this.buffer=t.buffer,0==this.index&&this.maybeNext()}static create(t,e=t.bufferBase+t.buffer.length){return new Yp(t,e,e-t.bufferBase)}maybeNext(){let t=this.stack.parent;null!=t&&(this.index=this.stack.bufferBase-t.bufferBase,this.stack=t,this.buffer=t.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,0==this.index&&this.maybeNext()}fork(){return new Yp(this.stack,this.pos,this.index)}}function Wp(t,e=Uint16Array){if("string"!=typeof t)return t;let i=null;for(let n=0,s=0;n<t.length;){let r=0;for(;;){let e=t.charCodeAt(n++),i=!1;if(126==e){r=65535;break}e>=92&&e--,e>=34&&e--;let s=e-32;if(s>=46&&(s-=46,i=!0),r+=s,i)break;r*=46}i?i[s++]=r:i=new e(r)}return i}class Mp{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}}const jp=new Mp;class Dp{constructor(t,e){this.input=t,this.ranges=e,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=jp,this.rangeIndex=0,this.pos=this.chunkPos=e[0].from,this.range=e[0],this.end=e[e.length-1].to,this.readNext()}resolveOffset(t,e){let i=this.range,n=this.rangeIndex,s=this.pos+t;for(;s<i.from;){if(!n)return null;let t=this.ranges[--n];s-=i.from-t.to,i=t}for(;e<0?s>i.to:s>=i.to;){if(n==this.ranges.length-1)return null;let t=this.ranges[++n];s+=t.from-i.to,i=t}return s}clipPos(t){if(t>=this.range.from&&t<this.range.to)return t;for(let e of this.ranges)if(e.to>t)return Math.max(t,e.from);return this.end}peek(t){let e,i,n=this.chunkOff+t;if(n>=0&&n<this.chunk.length)e=this.pos+t,i=this.chunk.charCodeAt(n);else{let n=this.resolveOffset(t,1);if(null==n)return-1;if(e=n,e>=this.chunk2Pos&&e<this.chunk2Pos+this.chunk2.length)i=this.chunk2.charCodeAt(e-this.chunk2Pos);else{let t=this.rangeIndex,n=this.range;for(;n.to<=e;)n=this.ranges[++t];this.chunk2=this.input.chunk(this.chunk2Pos=e),e+this.chunk2.length>n.to&&(this.chunk2=this.chunk2.slice(0,n.to-e)),i=this.chunk2.charCodeAt(0)}}return e>=this.token.lookAhead&&(this.token.lookAhead=e+1),i}acceptToken(t,e=0){let i=e?this.resolveOffset(e,-1):this.pos;if(null==i||i<this.token.start)throw new RangeError("Token end out of bounds");this.token.value=t,this.token.end=i}acceptTokenTo(t,e){this.token.value=t,this.token.end=e}getChunk(){if(this.pos>=this.chunk2Pos&&this.pos<this.chunk2Pos+this.chunk2.length){let{chunk:t,chunkPos:e}=this;this.chunk=this.chunk2,this.chunkPos=this.chunk2Pos,this.chunk2=t,this.chunk2Pos=e,this.chunkOff=this.pos-this.chunkPos}else{this.chunk2=this.chunk,this.chunk2Pos=this.chunkPos;let t=this.input.chunk(this.pos),e=this.pos+t.length;this.chunk=e>this.range.to?t.slice(0,this.range.to-this.pos):t,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(t=1){for(this.chunkOff+=t;this.pos+t>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();t-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=t,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(t,e){if(e?(this.token=e,e.start=t,e.lookAhead=t+1,e.value=e.extended=-1):this.token=jp,this.pos!=t){if(this.pos=t,t==this.end)return this.setDone(),this;for(;t<this.range.from;)this.range=this.ranges[--this.rangeIndex];for(;t>=this.range.to;)this.range=this.ranges[++this.rangeIndex];t>=this.chunkPos&&t<this.chunkPos+this.chunk.length?this.chunkOff=t-this.chunkPos:(this.chunk="",this.chunkOff=0),this.readNext()}return this}read(t,e){if(t>=this.chunkPos&&e<=this.chunkPos+this.chunk.length)return this.chunk.slice(t-this.chunkPos,e-this.chunkPos);if(t>=this.chunk2Pos&&e<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(t-this.chunk2Pos,e-this.chunk2Pos);if(t>=this.range.from&&e<=this.range.to)return this.input.read(t,e);let i="";for(let n of this.ranges){if(n.from>=e)break;n.to>t&&(i+=this.input.read(Math.max(n.from,t),Math.min(n.to,e)))}return i}}class Ep{constructor(t,e){this.data=t,this.id=e}token(t,e){let{parser:i}=e.p;Vp(this.data,t,e,this.id,i.data,i.tokenPrecTable)}}Ep.prototype.contextual=Ep.prototype.fallback=Ep.prototype.extend=!1;class qp{constructor(t,e,i){this.precTable=e,this.elseToken=i,this.data="string"==typeof t?Wp(t):t}token(t,e){let i=t.pos,n=0;for(;;){let i=t.next<0,s=t.resolveOffset(1,1);if(Vp(this.data,t,e,0,this.data,this.precTable),t.token.value>-1)break;if(null==this.elseToken)return;if(i||n++,null==s)break;t.reset(s,t.token)}n&&(t.reset(i,t.token),t.acceptToken(this.elseToken,n))}}qp.prototype.contextual=Ep.prototype.fallback=Ep.prototype.extend=!1;class _p{constructor(t,e={}){this.token=t,this.contextual=!!e.contextual,this.fallback=!!e.fallback,this.extend=!!e.extend}}function Vp(t,e,i,n,s,r){let o=0,a=1<<n,{dialect:l}=i.p.parser;t:for(;0!=(a&t[o]);){let i=t[o+1];for(let n=o+3;n<i;n+=2)if((t[n+1]&a)>0){let i=t[n];if(l.allows(i)&&(-1==e.token.value||e.token.value==i||zp(i,e.token.value,s,r))){e.acceptToken(i);break}}let n=e.next,h=0,c=t[o+2];if(!(e.next<0&&c>h&&65535==t[i+3*c-3])){for(;h<c;){let s=h+c>>1,r=i+s+(s<<1),a=t[r],l=t[r+1]||65536;if(n<a)c=s;else{if(!(n>=l)){o=t[r+2],e.advance();continue t}h=s+1}}break}o=t[i+3*c-1]}}function Ip(t,e,i){for(let n,s=e;65535!=(n=t[s]);s++)if(n==i)return s-e;return-1}function zp(t,e,i,n){let s=Ip(i,n,e);return s<0||Ip(i,n,t)<s}const Bp="undefined"!=typeof process&&process.env&&/\bparse\b/.test(process.env.LOG);let Gp=null;function Lp(t,e,i){let n=t.cursor(ra.IncludeAnonymous);for(n.moveTo(e);;)if(!(i<0?n.childBefore(e):n.childAfter(e)))for(;;){if((i<0?n.to<e:n.from>e)&&!n.type.isError)return i<0?Math.max(0,Math.min(n.to-1,e-25)):Math.min(t.length,Math.max(n.from+1,e+25));if(i<0?n.prevSibling():n.nextSibling())break;if(!n.parent())return i<0?0:t.length}}class Np{constructor(t,e){this.fragments=t,this.nodeSet=e,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let t=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(t){for(this.safeFrom=t.openStart?Lp(t.tree,t.from+t.offset,1)-t.offset:t.from,this.safeTo=t.openEnd?Lp(t.tree,t.to+t.offset,-1)-t.offset:t.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(t.tree),this.start.push(-t.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(t){if(t<this.nextStart)return null;for(;this.fragment&&this.safeTo<=t;)this.nextFragment();if(!this.fragment)return null;for(;;){let e=this.trees.length-1;if(e<0)return this.nextFragment(),null;let i=this.trees[e],n=this.index[e];if(n==i.children.length){this.trees.pop(),this.start.pop(),this.index.pop();continue}let s=i.children[n],r=this.start[e]+i.positions[n];if(r>t)return this.nextStart=r,null;if(s instanceof oa){if(r==t){if(r<this.safeFrom)return null;let t=r+s.length;if(t<=this.safeTo){let e=s.prop(Jo.lookAhead);if(!e||t+e<this.fragment.to)return s}}this.index[e]++,r+s.length>=Math.max(this.safeFrom,t)&&(this.trees.push(s),this.start.push(r),this.index.push(0))}else this.index[e]++,this.nextStart=r+s.length}}}class Up{constructor(t,e){this.stream=e,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=t.tokenizers.map((t=>new Mp))}getActions(t){let e=0,i=null,{parser:n}=t.p,{tokenizers:s}=n,r=n.stateSlot(t.state,3),o=t.curContext?t.curContext.hash:0,a=0;for(let n=0;n<s.length;n++){if(0==(1<<n&r))continue;let l=s[n],h=this.tokens[n];if((!i||l.fallback)&&((l.contextual||h.start!=t.pos||h.mask!=r||h.context!=o)&&(this.updateCachedToken(h,l,t),h.mask=r,h.context=o),h.lookAhead>h.end+25&&(a=Math.max(h.lookAhead,a)),0!=h.value)){let n=e;if(h.extended>-1&&(e=this.addActions(t,h.extended,h.end,e)),e=this.addActions(t,h.value,h.end,e),!l.extend&&(i=h,e>n))break}}for(;this.actions.length>e;)this.actions.pop();return a&&t.setLookAhead(a),i||t.pos!=this.stream.end||(i=new Mp,i.value=t.p.parser.eofTerm,i.start=i.end=t.pos,e=this.addActions(t,i.value,i.end,e)),this.mainToken=i,this.actions}getMainToken(t){if(this.mainToken)return this.mainToken;let e=new Mp,{pos:i,p:n}=t;return e.start=i,e.end=Math.min(i+1,n.stream.end),e.value=i==n.stream.end?n.parser.eofTerm:0,e}updateCachedToken(t,e,i){let n=this.stream.clipPos(i.pos);if(e.token(this.stream.reset(n,t),i),t.value>-1){let{parser:e}=i.p;for(let n=0;n<e.specialized.length;n++)if(e.specialized[n]==t.value){let s=e.specializers[n](this.stream.read(t.start,t.end),i);if(s>=0&&i.p.parser.dialect.allows(s>>1)){0==(1&s)?t.value=s>>1:t.extended=s>>1;break}}}else t.value=0,t.end=this.stream.clipPos(n+1)}putAction(t,e,i,n){for(let e=0;e<n;e+=3)if(this.actions[e]==t)return n;return this.actions[n++]=t,this.actions[n++]=e,this.actions[n++]=i,n}addActions(t,e,i,n){let{state:s}=t,{parser:r}=t.p,{data:o}=r;for(let t=0;t<2;t++)for(let a=r.stateSlot(s,t?2:1);;a+=3){if(65535==o[a]){if(1!=o[a+1]){0==n&&2==o[a+1]&&(n=this.putAction(eO(o,a+2),e,i,n));break}a=eO(o,a+2)}o[a]==e&&(n=this.putAction(eO(o,a+1),e,i,n))}return n}}class Hp{constructor(t,e,i,n){this.parser=t,this.input=e,this.ranges=n,this.recovering=0,this.nextStackID=9812,this.minStackPos=0,this.reused=[],this.stoppedAt=null,this.lastBigReductionStart=-1,this.lastBigReductionSize=0,this.bigReductionCount=0,this.stream=new Dp(e,n),this.tokens=new Up(t,this.stream),this.topTerm=t.top[1];let{from:s}=n[0];this.stacks=[Ap.start(this,t.top[0],s)],this.fragments=i.length&&this.stream.end-s>4*t.bufferLength?new Np(i,t.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let t,e,i=this.stacks,n=this.minStackPos,s=this.stacks=[];if(this.bigReductionCount>300&&1==i.length){let[t]=i;for(;t.forceReduce()&&t.stack.length&&t.stack[t.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let r=0;r<i.length;r++){let o=i[r];for(;;){if(this.tokens.mainToken=null,o.pos>n)s.push(o);else{if(this.advanceStack(o,s,i))continue;{t||(t=[],e=[]),t.push(o);let i=this.tokens.getMainToken(o);e.push(i.value,i.end)}}break}}if(!s.length){let e=t&&function(t){let e=null;for(let i of t){let t=i.p.stoppedAt;(i.pos==i.p.stream.end||null!=t&&i.pos>t)&&i.p.parser.stateFlag(i.state,2)&&(!e||e.score<i.score)&&(e=i)}return e}(t);if(e)return Bp&&console.log("Finish with "+this.stackID(e)),this.stackToTree(e);if(this.parser.strict)throw Bp&&t&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+n);this.recovering||(this.recovering=5)}if(this.recovering&&t){let i=null!=this.stoppedAt&&t[0].pos>this.stoppedAt?t[0]:this.runRecovery(t,e,s);if(i)return Bp&&console.log("Force-finish "+this.stackID(i)),this.stackToTree(i.forceAll())}if(this.recovering){let t=1==this.recovering?1:3*this.recovering;if(s.length>t)for(s.sort(((t,e)=>e.score-t.score));s.length>t;)s.pop();s.some((t=>t.reducePos>n))&&this.recovering--}else if(s.length>1){t:for(let t=0;t<s.length-1;t++){let e=s[t];for(let i=t+1;i<s.length;i++){let n=s[i];if(e.sameState(n)||e.buffer.length>500&&n.buffer.length>500){if(!((e.score-n.score||e.buffer.length-n.buffer.length)>0)){s.splice(t--,1);continue t}s.splice(i--,1)}}}s.length>12&&s.splice(12,s.length-12)}this.minStackPos=s[0].pos;for(let t=1;t<s.length;t++)s[t].pos<this.minStackPos&&(this.minStackPos=s[t].pos);return null}stopAt(t){if(null!=this.stoppedAt&&this.stoppedAt<t)throw new RangeError("Can't move stoppedAt forward");this.stoppedAt=t}advanceStack(t,e,i){let n=t.pos,{parser:s}=this,r=Bp?this.stackID(t)+" -> ":"";if(null!=this.stoppedAt&&n>this.stoppedAt)return t.forceReduce()?t:null;if(this.fragments){let e=t.curContext&&t.curContext.tracker.strict,i=e?t.curContext.hash:0;for(let o=this.fragments.nodeAt(n);o;){let n=this.parser.nodeSet.types[o.type.id]==o.type?s.getGoto(t.state,o.type.id):-1;if(n>-1&&o.length&&(!e||(o.prop(Jo.contextHash)||0)==i))return t.useNode(o,n),Bp&&console.log(r+this.stackID(t)+` (via reuse of ${s.getName(o.type.id)})`),!0;if(!(o instanceof oa)||0==o.children.length||o.positions[0]>0)break;let a=o.children[0];if(!(a instanceof oa&&0==o.positions[0]))break;o=a}}let o=s.stateSlot(t.state,4);if(o>0)return t.reduce(o),Bp&&console.log(r+this.stackID(t)+` (via always-reduce ${s.getName(65535&o)})`),!0;if(t.stack.length>=8400)for(;t.stack.length>6e3&&t.forceReduce(););let a=this.tokens.getActions(t);for(let o=0;o<a.length;){let l=a[o++],h=a[o++],c=a[o++],f=o==a.length||!i,u=f?t:t.split(),d=this.tokens.mainToken;if(u.apply(l,h,d?d.start:u.pos,c),Bp&&console.log(r+this.stackID(u)+` (via ${0==(65536&l)?"shift":`reduce of ${s.getName(65535&l)}`} for ${s.getName(h)} @ ${n}${u==t?"":", split"})`),f)return!0;u.pos>n?e.push(u):i.push(u)}return!1}advanceFully(t,e){let i=t.pos;for(;;){if(!this.advanceStack(t,null,null))return!1;if(t.pos>i)return Fp(t,e),!0}}runRecovery(t,e,i){let n=null,s=!1;for(let r=0;r<t.length;r++){let o=t[r],a=e[r<<1],l=e[1+(r<<1)],h=Bp?this.stackID(o)+" -> ":"";if(o.deadEnd){if(s)continue;if(s=!0,o.restart(),Bp&&console.log(h+this.stackID(o)+" (restarted)"),this.advanceFully(o,i))continue}let c=o.split(),f=h;for(let t=0;c.forceReduce()&&t<10;t++){if(Bp&&console.log(f+this.stackID(c)+" (via force-reduce)"),this.advanceFully(c,i))break;Bp&&(f=this.stackID(c)+" -> ")}for(let t of o.recoverByInsert(a))Bp&&console.log(h+this.stackID(t)+" (via recover-insert)"),this.advanceFully(t,i);this.stream.end>o.pos?(l==o.pos&&(l++,a=0),o.recoverByDelete(a,l),Bp&&console.log(h+this.stackID(o)+` (via recover-delete ${this.parser.getName(a)})`),Fp(o,i)):(!n||n.score<o.score)&&(n=o)}return n}stackToTree(t){return t.close(),oa.build({buffer:Yp.create(t),nodeSet:this.parser.nodeSet,topID:this.topTerm,maxBufferLength:this.parser.bufferLength,reused:this.reused,start:this.ranges[0].from,length:t.pos-this.ranges[0].from,minRepeatType:this.parser.minRepeatTerm})}stackID(t){let e=(Gp||(Gp=new WeakMap)).get(t);return e||Gp.set(t,e=String.fromCodePoint(this.nextStackID++)),e+t}}function Fp(t,e){for(let i=0;i<e.length;i++){let n=e[i];if(n.pos==t.pos&&n.sameState(t))return void(e[i].score<t.score&&(e[i]=t))}e.push(t)}class Jp{constructor(t,e,i){this.source=t,this.flags=e,this.disabled=i}allows(t){return!this.disabled||0==this.disabled[t]}}const Kp=t=>t;class tO extends $a{constructor(t){if(super(),this.wrappers=[],14!=t.version)throw new RangeError(`Parser version (${t.version}) doesn't match runtime version (14)`);let e=t.nodeNames.split(" ");this.minRepeatTerm=e.length;for(let i=0;i<t.repeatNodeCount;i++)e.push("");let i=Object.keys(t.topRules).map((e=>t.topRules[e][1])),n=[];for(let t=0;t<e.length;t++)n.push([]);function s(t,e,i){n[t].push([e,e.deserialize(String(i))])}if(t.nodeProps)for(let e of t.nodeProps){let t=e[0];"string"==typeof t&&(t=Jo[t]);for(let i=1;i<e.length;){let n=e[i++];if(n>=0)s(n,t,e[i++]);else{let r=e[i+-n];for(let o=-n;o>0;o--)s(e[i++],t,r);i++}}}this.nodeSet=new ia(e.map(((e,s)=>ea.define({name:s>=this.minRepeatTerm?void 0:e,id:s,props:n[s],top:i.indexOf(s)>-1,error:0==s,skipped:t.skippedNodes&&t.skippedNodes.indexOf(s)>-1})))),t.propSources&&(this.nodeSet=this.nodeSet.extend(...t.propSources)),this.strict=!1,this.bufferLength=Uo;let r=Wp(t.tokenData);this.context=t.context,this.specializerSpecs=t.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let t=0;t<this.specializerSpecs.length;t++)this.specialized[t]=this.specializerSpecs[t].term;this.specializers=this.specializerSpecs.map(iO),this.states=Wp(t.states,Uint32Array),this.data=Wp(t.stateData),this.goto=Wp(t.goto),this.maxTerm=t.maxTerm,this.tokenizers=t.tokenizers.map((t=>"number"==typeof t?new Ep(r,t):t)),this.topRules=t.topRules,this.dialects=t.dialects||{},this.dynamicPrecedences=t.dynamicPrecedences||null,this.tokenPrecTable=t.tokenPrec,this.termNames=t.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(t,e,i){let n=new Hp(this,t,e,i);for(let s of this.wrappers)n=s(n,t,e,i);return n}getGoto(t,e,i=!1){let n=this.goto;if(e>=n[0])return-1;for(let s=n[e+1];;){let e=n[s++],r=1&e,o=n[s++];if(r&&i)return o;for(let i=s+(e>>1);s<i;s++)if(n[s]==t)return o;if(r)return-1}}hasAction(t,e){let i=this.data;for(let n=0;n<2;n++)for(let s,r=this.stateSlot(t,n?2:1);;r+=3){if(65535==(s=i[r])){if(1!=i[r+1]){if(2==i[r+1])return eO(i,r+2);break}s=i[r=eO(i,r+2)]}if(s==e||0==s)return eO(i,r+1)}return 0}stateSlot(t,e){return this.states[6*t+e]}stateFlag(t,e){return(this.stateSlot(t,0)&e)>0}validAction(t,e){return!!this.allActions(t,(t=>t==e||null))}allActions(t,e){let i=this.stateSlot(t,4),n=i?e(i):void 0;for(let i=this.stateSlot(t,1);null==n;i+=3){if(65535==this.data[i]){if(1!=this.data[i+1])break;i=eO(this.data,i+2)}n=e(eO(this.data,i+1))}return n}nextStates(t){let e=[];for(let i=this.stateSlot(t,1);;i+=3){if(65535==this.data[i]){if(1!=this.data[i+1])break;i=eO(this.data,i+2)}if(0==(1&this.data[i+2])){let t=this.data[i+1];e.some(((e,i)=>1&i&&e==t))||e.push(this.data[i],t)}}return e}configure(t){let e=Object.assign(Object.create(tO.prototype),this);if(t.props&&(e.nodeSet=this.nodeSet.extend(...t.props)),t.top){let i=this.topRules[t.top];if(!i)throw new RangeError(`Invalid top rule name ${t.top}`);e.top=i}return t.tokenizers&&(e.tokenizers=this.tokenizers.map((e=>{let i=t.tokenizers.find((t=>t.from==e));return i?i.to:e}))),t.specializers&&(e.specializers=this.specializers.slice(),e.specializerSpecs=this.specializerSpecs.map(((i,n)=>{let s=t.specializers.find((t=>t.from==i.external));if(!s)return i;let r=Object.assign(Object.assign({},i),{external:s.to});return e.specializers[n]=iO(r),r}))),t.contextTracker&&(e.context=t.contextTracker),t.dialect&&(e.dialect=this.parseDialect(t.dialect)),null!=t.strict&&(e.strict=t.strict),t.wrap&&(e.wrappers=e.wrappers.concat(t.wrap)),null!=t.bufferLength&&(e.bufferLength=t.bufferLength),e}hasWrappers(){return this.wrappers.length>0}getName(t){return this.termNames?this.termNames[t]:String(t<=this.maxNode&&this.nodeSet.types[t].name||t)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(t){let e=this.dynamicPrecedences;return null==e?0:e[t]||0}parseDialect(t){let e=Object.keys(this.dialects),i=e.map((()=>!1));if(t)for(let n of t.split(" ")){let t=e.indexOf(n);t>=0&&(i[t]=!0)}let n=null;for(let t=0;t<e.length;t++)if(!i[t])for(let i,s=this.dialects[e[t]];65535!=(i=this.data[s++]);)(n||(n=new Uint8Array(this.maxTerm+1)))[i]=1;return new Jp(t,i,n)}static deserialize(t){return new tO(t)}}function eO(t,e){return t[e]|t[e+1]<<16}function iO(t){if(t.external){let e=t.extend?1:0;return(i,n)=>t.external(i,n)<<1|e}return t.get}const nO=[9,10,11,12,13,32,133,160,5760,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8232,8233,8239,8287,12288],sO=new class{constructor(t){this.start=t.start,this.shift=t.shift||Kp,this.reduce=t.reduce||Kp,this.reuse=t.reuse||Kp,this.hash=t.hash||(()=>0),this.strict=!1!==t.strict}}({start:!1,shift:(t,e)=>4==e||5==e||312==e?t:313==e,strict:!1}),rO=new _p(((t,e)=>{let{next:i}=t;(125==i||-1==i||e.context)&&t.acceptToken(310)}),{contextual:!0,fallback:!0}),oO=new _p(((t,e)=>{let i,{next:n}=t;nO.indexOf(n)>-1||(47!=n||47!=(i=t.peek(1))&&42!=i)&&(125==n||59==n||-1==n||e.context||t.acceptToken(309))}),{contextual:!0}),aO=new _p(((t,e)=>{let{next:i}=t;if((43==i||45==i)&&(t.advance(),i==t.next)){t.advance();let i=!e.context&&e.canShift(1);t.acceptToken(i?1:2)}}),{contextual:!0});function lO(t,e){return t>=65&&t<=90||t>=97&&t<=122||95==t||t>=192||!e&&t>=48&&t<=57}const hO=new _p(((t,e)=>{if(60!=t.next||!e.dialectEnabled(0))return;if(t.advance(),47==t.next)return;let i=0;for(;nO.indexOf(t.next)>-1;)t.advance(),i++;if(lO(t.next,!0)){for(t.advance(),i++;lO(t.next,!1);)t.advance(),i++;for(;nO.indexOf(t.next)>-1;)t.advance(),i++;if(44==t.next)return;for(let e=0;;e++){if(7==e){if(!lO(t.next,!0))return;break}if(t.next!="extends".charCodeAt(e))break;t.advance(),i++}}t.acceptToken(3,-i)})),cO=Ra({"get set async static":tl.modifier,"for while do if else switch try catch finally return throw break continue default case":tl.controlKeyword,"in of await yield void typeof delete instanceof":tl.operatorKeyword,"let var const using function class extends":tl.definitionKeyword,"import export from":tl.moduleKeyword,"with debugger as new":tl.keyword,TemplateString:tl.special(tl.string),super:tl.atom,BooleanLiteral:tl.bool,this:tl.self,null:tl.null,Star:tl.modifier,VariableName:tl.variableName,"CallExpression/VariableName TaggedTemplateExpression/VariableName":tl.function(tl.variableName),VariableDefinition:tl.definition(tl.variableName),Label:tl.labelName,PropertyName:tl.propertyName,PrivatePropertyName:tl.special(tl.propertyName),"CallExpression/MemberExpression/PropertyName":tl.function(tl.propertyName),"FunctionDeclaration/VariableDefinition":tl.function(tl.definition(tl.variableName)),"ClassDeclaration/VariableDefinition":tl.definition(tl.className),PropertyDefinition:tl.definition(tl.propertyName),PrivatePropertyDefinition:tl.definition(tl.special(tl.propertyName)),UpdateOp:tl.updateOperator,"LineComment Hashbang":tl.lineComment,BlockComment:tl.blockComment,Number:tl.number,String:tl.string,Escape:tl.escape,ArithOp:tl.arithmeticOperator,LogicOp:tl.logicOperator,BitOp:tl.bitwiseOperator,CompareOp:tl.compareOperator,RegExp:tl.regexp,Equals:tl.definitionOperator,Arrow:tl.function(tl.punctuation),": Spread":tl.punctuation,"( )":tl.paren,"[ ]":tl.squareBracket,"{ }":tl.brace,"InterpolationStart InterpolationEnd":tl.special(tl.brace),".":tl.derefOperator,", ;":tl.separator,"@":tl.meta,TypeName:tl.typeName,TypeDefinition:tl.definition(tl.typeName),"type enum interface implements namespace module declare":tl.definitionKeyword,"abstract global Privacy readonly override":tl.modifier,"is keyof unique infer":tl.operatorKeyword,JSXAttributeValue:tl.attributeValue,JSXText:tl.content,"JSXStartTag JSXStartCloseTag JSXSelfCloseEndTag JSXEndTag":tl.angleBracket,"JSXIdentifier JSXNameSpacedName":tl.tagName,"JSXAttribute/JSXIdentifier JSXAttribute/JSXNameSpacedName":tl.attributeName,"JSXBuiltin/JSXIdentifier":tl.standard(tl.tagName)}),fO={__proto__:null,export:18,as:23,from:31,default:34,async:39,function:40,extends:52,this:56,true:64,false:64,null:76,void:80,typeof:84,super:102,new:136,delete:152,yield:161,await:165,class:170,public:227,private:227,protected:227,readonly:229,instanceof:248,satisfies:251,in:252,const:254,import:286,keyof:339,unique:343,infer:349,is:385,abstract:405,implements:407,type:409,let:412,var:414,using:417,interface:423,enum:427,namespace:433,module:435,declare:439,global:443,for:462,of:471,while:474,with:478,do:482,if:486,else:488,switch:492,case:498,try:504,catch:508,finally:512,return:516,throw:520,break:524,continue:528,debugger:532},uO={__proto__:null,async:123,get:125,set:127,declare:187,public:189,private:189,protected:189,static:191,abstract:193,override:195,readonly:201,accessor:203,new:389},dO={__proto__:null,"<":143},pO=tO.deserialize({version:14,states:"$<UO%TQ^OOO%[Q^OOO'_Q`OOP(lOWOOO*zQ08SO'#ChO+RO!bO'#CiO+aO#tO'#CiO+oO?MpO'#D^O.QQ^O'#DdO.bQ^O'#DoO%[Q^O'#DyO0fQ^O'#EROOQ07b'#EZ'#EZO1PQWO'#EWOOQO'#El'#ElOOQO'#Ie'#IeO1XQWO'#GmO1dQWO'#EkO1iQWO'#EkO3kQ08SO'#JiO6[Q08SO'#JjO6xQWO'#FZO6}Q&jO'#FqOOQ07b'#Fc'#FcO7YO,YO'#FcO7hQ7[O'#FxO9UQWO'#FwOOQ07b'#Jj'#JjOOQ07`'#Ji'#JiO9ZQWO'#GqOOQU'#KU'#KUO9fQWO'#IRO9kQ07hO'#ISOOQU'#JW'#JWOOQU'#IW'#IWQ`Q^OOO`Q^OOO%[Q^O'#DqO9sQ^O'#D}O9zQ^O'#EPO9aQWO'#GmO:RQ7[O'#CnO:aQWO'#EjO:lQWO'#EuO:qQ7[O'#FbO;`QWO'#GmOOQO'#KV'#KVO;eQWO'#KVO;sQWO'#GuO;sQWO'#GvO;sQWO'#GxO9aQWO'#G{O<jQWO'#HOO>RQWO'#CdO>cQWO'#H[O>kQWO'#HbO>kQWO'#HdO`Q^O'#HfO>kQWO'#HhO>kQWO'#HkO>pQWO'#HqO>uQ07iO'#HwO%[Q^O'#HyO?QQ07iO'#H{O?]Q07iO'#H}O9kQ07hO'#IPO?hQ08SO'#ChO@jQ`O'#DiQOQWOOO%[Q^O'#EPOAQQWO'#ESO:RQ7[O'#EjOA]QWO'#EjOAhQpO'#FbOOQU'#Cf'#CfOOQ07`'#Dn'#DnOOQ07`'#Jm'#JmO%[Q^O'#JmOOQO'#Jq'#JqOOQO'#Ib'#IbOBhQ`O'#EcOOQ07`'#Eb'#EbOCdQ07pO'#EcOCnQ`O'#EVOOQO'#Jp'#JpODSQ`O'#JqOEaQ`O'#EVOCnQ`O'#EcPEnO!0LbO'#CaPOOO)CDu)CDuOOOO'#IX'#IXOEyO!bO,59TOOQ07b,59T,59TOOOO'#IY'#IYOFXO#tO,59TO%[Q^O'#D`OOOO'#I['#I[OFgO?MpO,59xOOQ07b,59x,59xOFuQ^O'#I]OGYQWO'#JkOI[QrO'#JkO+}Q^O'#JkOIcQWO,5:OOIyQWO'#ElOJWQWO'#JyOJcQWO'#JxOJcQWO'#JxOJkQWO,5;YOJpQWO'#JwOOQ07f,5:Z,5:ZOJwQ^O,5:ZOLxQ08SO,5:eOMiQWO,5:mONSQ07hO'#JvONZQWO'#JuO9ZQWO'#JuONoQWO'#JuONwQWO,5;XON|QWO'#JuO!#UQrO'#JjOOQ07b'#Ch'#ChO%[Q^O'#ERO!#tQpO,5:rOOQO'#Jr'#JrOOQO-E<c-E<cO9aQWO,5=XO!$[QWO,5=XO!$aQ^O,5;VO!&dQ7[O'#EgO!'}QWO,5;VO!)mQ7[O'#DsO!)tQ^O'#DxO!*OQ`O,5;`O!*WQ`O,5;`O%[Q^O,5;`OOQU'#FR'#FROOQU'#FT'#FTO%[Q^O,5;aO%[Q^O,5;aO%[Q^O,5;aO%[Q^O,5;aO%[Q^O,5;aO%[Q^O,5;aO%[Q^O,5;aO%[Q^O,5;aO%[Q^O,5;aO%[Q^O,5;aO%[Q^O,5;aOOQU'#FX'#FXO!*fQ^O,5;rOOQ07b,5;w,5;wOOQ07b,5;x,5;xO!,iQWO,5;xOOQ07b,5;y,5;yO%[Q^O'#IiO!,qQ07hO,5<eO!&dQ7[O,5;aO!-`Q7[O,5;aO%[Q^O,5;uO!-gQ&jO'#FgO!.dQ&jO'#J}O!.OQ&jO'#J}O!.kQ&jO'#J}OOQO'#J}'#J}O!/PQ&jO,5<POOOS,5<],5<]O!/bQ^O'#FsOOOS'#Ih'#IhO7YO,YO,5;}O!/iQ&jO'#FuOOQ07b,5;},5;}O!0YQMhO'#CuOOQ07b'#Cy'#CyO!0mQWO'#CyO!0rO?MpO'#C}O!1`Q7[O,5<bO!1gQWO,5<dO!3SQ!LQO'#GSO!3aQWO'#GTO!3fQWO'#GTO!3kQ!LQO'#GXO!4jQ`O'#G]OOQO'#Gh'#GhO!(SQ7[O'#GgOOQO'#Gj'#GjO!(SQ7[O'#GiO!5]QMhO'#JdOOQ07b'#Jd'#JdO!5gQWO'#JcO!5uQWO'#JbO!5}QWO'#CtOOQ07b'#Cw'#CwOOQ07b'#DR'#DROOQ07b'#DT'#DTO1SQWO'#DVO!(SQ7[O'#FzO!(SQ7[O'#F|O!6VQWO'#GOO!6[QWO'#GPO!3fQWO'#GVO!(SQ7[O'#G[O!6aQWO'#EmO!7OQWO,5<cOOQ07`'#Cq'#CqO!7WQWO'#EnO!8QQ`O'#EoOOQ07`'#Jw'#JwO!8XQ07hO'#KWO9kQ07hO,5=]O`Q^O,5>mOOQU'#J`'#J`OOQU,5>n,5>nOOQU-E<U-E<UO!:ZQ08SO,5:]O!<wQ08SO,5:iO%[Q^O,5:iO!?bQ08SO,5:kOOQO,5@q,5@qO!@RQ7[O,5=XO!@aQ07hO'#JaO9UQWO'#JaO!@rQ07hO,59YO!@}Q`O,59YO!AVQ7[O,59YO:RQ7[O,59YO!AbQWO,5;VO!AjQWO'#HZO!BOQWO'#KZO%[Q^O,5;zO!7{Q`O,5;|O!BWQWO,5=tO!B]QWO,5=tO!BbQWO,5=tO9kQ07hO,5=tO;sQWO,5=dOOQO'#Cu'#CuO!BpQ`O,5=aO!BxQ7[O,5=bO!CTQWO,5=dO!CYQpO,5=gO!CbQWO'#KVO>pQWO'#HQO9aQWO'#HSO!CgQWO'#HSO:RQ7[O'#HUO!ClQWO'#HUOOQU,5=j,5=jO!CqQWO'#HVO!DSQWO'#CnO!DXQWO,59OO!DcQWO,59OO!FhQ^O,59OOOQU,59O,59OO!FxQ07hO,59OO%[Q^O,59OO!ITQ^O'#H^OOQU'#H_'#H_OOQU'#H`'#H`O`Q^O,5=vO!IkQWO,5=vO`Q^O,5=|O`Q^O,5>OO!IpQWO,5>QO`Q^O,5>SO!IuQWO,5>VO!IzQ^O,5>]OOQU,5>c,5>cO%[Q^O,5>cO9kQ07hO,5>eOOQU,5>g,5>gO!NUQWO,5>gOOQU,5>i,5>iO!NUQWO,5>iOOQU,5>k,5>kO!NZQ`O'#D[O%[Q^O'#JmO!NxQ`O'#JmO# gQ`O'#DjO# xQ`O'#DjO#$ZQ^O'#DjO#$bQWO'#JlO#$jQWO,5:TO#$oQWO'#EpO#$}QWO'#JzO#%VQWO,5;ZO#%[Q`O'#DjO#%iQ`O'#EUOOQ07b,5:n,5:nO%[Q^O,5:nO#%pQWO,5:nO>pQWO,5;UO!@}Q`O,5;UO!AVQ7[O,5;UO:RQ7[O,5;UO#%xQWO,5@XO#%}Q$ISO,5:rOOQO-E<`-E<`O#'TQ07pO,5:}OCnQ`O,5:qO#'_Q`O,5:qOCnQ`O,5:}O!@rQ07hO,5:qOOQ07`'#Ef'#EfOOQO,5:},5:}O%[Q^O,5:}O#'lQ07hO,5:}O#'wQ07hO,5:}O!@}Q`O,5:qOOQO,5;T,5;TO#(VQ07hO,5:}POOO'#IV'#IVP#(kO!0LbO,58{POOO,58{,58{OOOO-E<V-E<VOOQ07b1G.o1G.oOOOO-E<W-E<WO#(vQpO,59zOOOO-E<Y-E<YOOQ07b1G/d1G/dO#({QrO,5>wO+}Q^O,5>wOOQO,5>},5>}O#)VQ^O'#I]OOQO-E<Z-E<ZO#)dQWO,5@VO#)lQrO,5@VO#)sQWO,5@dOOQ07b1G/j1G/jO%[Q^O,5@eO#){QWO'#IcOOQO-E<a-E<aO#)sQWO,5@dOOQ07`1G0t1G0tOOQ07f1G/u1G/uOOQ07f1G0X1G0XO%[Q^O,5@bO#*aQ07hO,5@bO#*rQ07hO,5@bO#*yQWO,5@aO9ZQWO,5@aO#+RQWO,5@aO#+aQWO'#IfO#*yQWO,5@aOOQ07`1G0s1G0sO!*OQ`O,5:tO!*ZQ`O,5:tOOQO,5:v,5:vO#,RQWO,5:vO#,ZQ7[O1G2sO9aQWO1G2sOOQ07b1G0q1G0qO#,iQ08SO1G0qO#-nQ08QO,5;ROOQ07b'#GR'#GRO#.[Q08SO'#JdO!$aQ^O1G0qO#0dQ7[O'#JnO#0nQWO,5:_O#0sQrO'#JoO%[Q^O'#JoO#0}QWO,5:dOOQ07b'#D['#D[OOQ07b1G0z1G0zO%[Q^O1G0zOOQ07b1G1d1G1dO#1SQWO1G0zO#3kQ08SO1G0{O#3rQ08SO1G0{O#6]Q08SO1G0{O#6dQ08SO1G0{O#8nQ08SO1G0{O#9UQ08SO1G0{O#<OQ08SO1G0{O#<VQ08SO1G0{O#>jQ08SO1G0{O#>wQ08SO1G0{O#@uQ08SO1G0{O#CuQ(CYO'#ChO#EsQ(CYO1G1^O#EzQ(CYO'#JjO!,lQWO1G1dO#F[Q08SO,5?TOOQ07`-E<g-E<gO#GOQ08SO1G0{OOQ07b1G0{1G0{O#IZQ08SO1G1aO#I}Q&jO,5<TO#JVQ&jO,5<UO#J_Q&jO'#FlO#JvQWO'#FkOOQO'#KO'#KOOOQO'#Ig'#IgO#J{Q&jO1G1kOOQ07b1G1k1G1kOOOS1G1v1G1vO#K^Q(CYO'#JiO#KhQWO,5<_O!*fQ^O,5<_OOOS-E<f-E<fOOQ07b1G1i1G1iO#KmQ`O'#J}OOQ07b,5<a,5<aO#KuQ`O,5<aOOQ07b,59e,59eO!&dQ7[O'#DPOOOO'#IZ'#IZO#KzO?MpO,59iOOQ07b,59i,59iO%[Q^O1G1|O!6[QWO'#IkO#LVQ7[O,5<uOOQ07b,5<r,5<rO!(SQ7[O'#InO#LuQ7[O,5=RO!(SQ7[O'#IpO#MhQ7[O,5=TO!&dQ7[O,5=VOOQO1G2O1G2OO#MrQpO'#CqO#NVQpO,5<nO#N^QWO'#KRO9aQWO'#KRO#NlQWO,5<pO!(SQ7[O,5<oO#NqQWO'#GUO#N|QWO,5<oO$ RQpO'#GRO$ `QpO'#KSO$ jQWO'#KSO!&dQ7[O'#KSO$ oQWO,5<sO$ tQ`O'#G^O!4eQ`O'#G^O$!VQWO'#G`O$![QWO'#GbO!3fQWO'#GeO$!aQ07hO'#ImO$!lQ`O,5<wOOQ07f,5<w,5<wO$!sQ`O'#G^O$#RQ`O'#G_O$#ZQ`O'#G_O$#`Q7[O,5=RO$#pQ7[O,5=TOOQ07b,5=W,5=WO!(SQ7[O,5?}O!(SQ7[O,5?}O$$QQWO'#IrO$$]QWO,5?|O$$eQWO,59`O$%UQ7[O,59qOOQ07b,59q,59qO$%wQ7[O,5<fO$&jQ7[O,5<hO@bQWO,5<jOOQ07b,5<k,5<kO$&tQWO,5<qO$&yQ7[O,5<vO$'ZQWO'#JuO!$aQ^O1G1}O$'`QWO1G1}O9ZQWO'#JxO9ZQWO'#EpO%[Q^O'#EpO9ZQWO'#ItO$'eQ07hO,5@rOOQU1G2w1G2wOOQU1G4X1G4XOOQ07b1G/w1G/wO!,iQWO1G/wO$)jQ08SO1G0TOOQU1G2s1G2sO!&dQ7[O1G2sO%[Q^O1G2sO#,^QWO1G2sO$+nQ7[O'#EgOOQ07`,5?{,5?{O$+xQ07hO,5?{OOQU1G.t1G.tO!@rQ07hO1G.tO!@}Q`O1G.tO!AVQ7[O1G.tO$,ZQWO1G0qO$,`QWO'#ChO$,kQWO'#K[O$,sQWO,5=uO$,xQWO'#K[O$,}QWO'#K[O$-]QWO'#IzO$-kQWO,5@uO$-sQrO1G1fOOQ07b1G1h1G1hO9aQWO1G3`O@bQWO1G3`O$-zQWO1G3`O$.PQWO1G3`OOQU1G3`1G3`O!CTQWO1G3OO!&dQ7[O1G2{O$.UQWO1G2{OOQU1G2|1G2|O!&dQ7[O1G2|O$.ZQWO1G2|O$.cQ`O'#GzOOQU1G3O1G3OO!4eQ`O'#IvO!CYQpO1G3ROOQU1G3R1G3ROOQU,5=l,5=lO$.kQ7[O,5=nO9aQWO,5=nO$![QWO,5=pO9UQWO,5=pO!@}Q`O,5=pO!AVQ7[O,5=pO:RQ7[O,5=pO$.yQWO'#KYO$/UQWO,5=qOOQU1G.j1G.jO$/ZQ07hO1G.jO@bQWO1G.jO$/fQWO1G.jO9kQ07hO1G.jO$1kQrO,5@wO$1{QWO,5@wO9ZQWO,5@wO$2WQ^O,5=xO$2_QWO,5=xOOQU1G3b1G3bO`Q^O1G3bOOQU1G3h1G3hOOQU1G3j1G3jO>kQWO1G3lO$2dQ^O1G3nO$6hQ^O'#HmOOQU1G3q1G3qO$6uQWO'#HsO>pQWO'#HuOOQU1G3w1G3wO$6}Q^O1G3wO9kQ07hO1G3}OOQU1G4P1G4POOQ07`'#GY'#GYO9kQ07hO1G4RO9kQ07hO1G4TO$;UQWO,5@XO!*fQ^O,5;[O9ZQWO,5;[O>pQWO,5:UO!*fQ^O,5:UO!@}Q`O,5:UO$;ZQ(CYO,5:UOOQO,5;[,5;[O$;eQ`O'#I^O$;{QWO,5@WOOQ07b1G/o1G/oO$<TQ`O'#IdO$<_QWO,5@fOOQ07`1G0u1G0uO# xQ`O,5:UOOQO'#Ia'#IaO$<gQ`O,5:pOOQ07f,5:p,5:pO#%sQWO1G0YOOQ07b1G0Y1G0YO%[Q^O1G0YOOQ07b1G0p1G0pO>pQWO1G0pO!@}Q`O1G0pO!AVQ7[O1G0pOOQ07`1G5s1G5sO!@rQ07hO1G0]OOQO1G0i1G0iO%[Q^O1G0iO$<nQ07hO1G0iO$<yQ07hO1G0iO!@}Q`O1G0]OCnQ`O1G0]O$=XQ07hO1G0iOOQO1G0]1G0]O$=mQ08SO1G0iPOOO-E<T-E<TPOOO1G.g1G.gOOOO1G/f1G/fO$=wQpO,5<eO$>PQrO1G4cOOQO1G4i1G4iO%[Q^O,5>wO$>ZQWO1G5qO$>cQWO1G6OO$>kQrO1G6PO9ZQWO,5>}O$>uQ08SO1G5|O%[Q^O1G5|O$?VQ07hO1G5|O$?hQWO1G5{O$?hQWO1G5{O9ZQWO1G5{O$?pQWO,5?QO9ZQWO,5?QOOQO,5?Q,5?QO$@UQWO,5?QO$'ZQWO,5?QOOQO-E<d-E<dOOQO1G0`1G0`OOQO1G0b1G0bO!,lQWO1G0bOOQU7+(_7+(_O!&dQ7[O7+(_O%[Q^O7+(_O$@dQWO7+(_O$@oQ7[O7+(_O$@}Q08SO,5=RO$CYQ08SO,5=TO$EeQ08SO,5=RO$GvQ08SO,5=TO$JXQ08SO,59qO$LaQ08SO,5<fO$NlQ08SO,5<hO%!wQ08SO,5<vOOQ07b7+&]7+&]O%%YQ08SO7+&]O%%|Q7[O'#I_O%&WQWO,5@YOOQ07b1G/y1G/yO%&`Q^O'#I`O%&mQWO,5@ZO%&uQrO,5@ZOOQ07b1G0O1G0OO%'PQWO7+&fOOQ07b7+&f7+&fO%'UQ(CYO,5:eO%[Q^O7+&xO%'`Q(CYO,5:]O%'mQ(CYO,5:iO%'wQ(CYO,5:kOOQ07b7+'O7+'OOOQO1G1o1G1oOOQO1G1p1G1pO%(RQtO,5<WO!*fQ^O,5<VOOQO-E<e-E<eOOQ07b7+'V7+'VOOOS7+'b7+'bOOOS1G1y1G1yO%(^QWO1G1yOOQ07b1G1{1G1{O%(cQpO,59kOOOO-E<X-E<XOOQ07b1G/T1G/TO%(jQ08SO7+'hOOQ07b,5?V,5?VO%)^QpO,5?VOOQ07b1G2a1G2aP!&dQ7[O'#IkPOQ07b-E<i-E<iO%)|Q7[O,5?YOOQ07b-E<l-E<lO%*oQ7[O,5?[OOQ07b-E<n-E<nO%*yQpO1G2qOOQ07b1G2Y1G2YO%+QQWO'#IjO%+`QWO,5@mO%+`QWO,5@mO%+hQWO,5@mO%+sQWO,5@mOOQO1G2[1G2[O%,RQ7[O1G2ZO!(SQ7[O1G2ZO%,cQ!LQO'#IlO%,sQWO,5@nO!&dQ7[O,5@nO%,{QpO,5@nOOQ07b1G2_1G2_OOQ07`,5<x,5<xOOQ07`,5<y,5<yO$'ZQWO,5<yOC_QWO,5<yO!@}Q`O,5<xOOQO'#Ga'#GaO%-VQWO,5<zOOQ07`,5<|,5<|O$'ZQWO,5=POOQO,5?X,5?XOOQO-E<k-E<kOOQ07f1G2c1G2cO!4eQ`O,5<xO%-_QWO,5<yO$!VQWO,5<zO!4eQ`O,5<yO!(SQ7[O'#InO%.RQ7[O1G2mO!(SQ7[O'#IpO%.tQ7[O1G2oO%/OQ7[O1G5iO%/YQ7[O1G5iOOQO,5?^,5?^OOQO-E<p-E<pOOQO1G.z1G.zO!7{Q`O,59sO%[Q^O,59sO%/gQWO1G2UO!(SQ7[O1G2]O%/lQ08SO7+'iOOQ07b7+'i7+'iO!$aQ^O7+'iO%0`QWO,5;[OOQ07`,5?`,5?`OOQ07`-E<r-E<rOOQ07b7+%c7+%cO%0eQpO'#KTO#%sQWO7+(_O%0oQrO7+(_O$@gQWO7+(_O%0vQ08QO'#ChO%1ZQ08QO,5<}O%1{QWO,5<}OOQ07`1G5g1G5gOOQU7+$`7+$`O!@rQ07hO7+$`O!@}Q`O7+$`O!$aQ^O7+&]O%2QQWO'#IyO%2iQWO,5@vOOQO1G3a1G3aO9aQWO,5@vO%2iQWO,5@vO%2qQWO,5@vOOQO,5?f,5?fOOQO-E<x-E<xOOQ07b7+'Q7+'QO%2vQWO7+(zO9kQ07hO7+(zO9aQWO7+(zO@bQWO7+(zOOQU7+(j7+(jO%2{Q08QO7+(gO!&dQ7[O7+(gO%3VQpO7+(hOOQU7+(h7+(hO!&dQ7[O7+(hO%3^QWO'#KXO%3iQWO,5=fOOQO,5?b,5?bOOQO-E<t-E<tOOQU7+(m7+(mO%4xQ`O'#HTOOQU1G3Y1G3YO!&dQ7[O1G3YO%[Q^O1G3YO%5PQWO1G3YO%5[Q7[O1G3YO9kQ07hO1G3[O$![QWO1G3[O9UQWO1G3[O!@}Q`O1G3[O!AVQ7[O1G3[O%5jQWO'#IxO%6OQWO,5@tO%6WQ`O,5@tOOQ07`1G3]1G3]OOQU7+$U7+$UO@bQWO7+$UO9kQ07hO7+$UO%6cQWO7+$UO%[Q^O1G6cO%[Q^O1G6dO%6hQ07hO1G6cO%6rQ^O1G3dO%6yQWO1G3dO%7OQ^O1G3dOOQU7+(|7+(|O9kQ07hO7+)WO`Q^O7+)YOOQU'#K_'#K_OOQU'#I{'#I{O%7VQ^O,5>XOOQU,5>X,5>XO%[Q^O'#HnO%7dQWO'#HpOOQU,5>_,5>_O9ZQWO,5>_OOQU,5>a,5>aOOQU7+)c7+)cOOQU7+)i7+)iOOQU7+)m7+)mOOQU7+)o7+)oO%7iQ`O1G5sO%7}Q(CYO1G0vO%8XQWO1G0vOOQO1G/p1G/pO%8dQ(CYO1G/pO>pQWO1G/pO!*fQ^O'#DjOOQO,5>x,5>xOOQO-E<[-E<[OOQO,5?O,5?OOOQO-E<b-E<bO!@}Q`O1G/pOOQO-E<_-E<_OOQ07f1G0[1G0[OOQ07b7+%t7+%tO#%sQWO7+%tOOQ07b7+&[7+&[O>pQWO7+&[O!@}Q`O7+&[OOQO7+%w7+%wO$=mQ08SO7+&TOOQO7+&T7+&TO%[Q^O7+&TO%8nQ07hO7+&TO!@rQ07hO7+%wO!@}Q`O7+%wO%8yQ07hO7+&TO%9XQ08SO7++hO%[Q^O7++hO%9iQWO7++gO%9iQWO7++gOOQO1G4l1G4lO9ZQWO1G4lO%9qQWO1G4lOOQO7+%|7+%|O#%sQWO<<KyO%0oQrO<<KyO%:PQWO<<KyOOQU<<Ky<<KyO!&dQ7[O<<KyO%[Q^O<<KyO%:XQWO<<KyO%:dQ08SO,5?YO%<oQ08SO,5?[O%>zQ08SO1G2ZO%A]Q08SO1G2mO%ChQ08SO1G2oO%EsQ7[O,5>yOOQO-E<]-E<]O%E}QrO,5>zO%[Q^O,5>zOOQO-E<^-E<^O%FXQWO1G5uOOQ07b<<JQ<<JQO%FaQ(CYO1G0qO%HkQ(CYO1G0{O%HrQ(CYO1G0{O%JvQ(CYO1G0{O%J}Q(CYO1G0{O%LrQ(CYO1G0{O%MYQ(CYO1G0{O& mQ(CYO1G0{O& tQ(CYO1G0{O&#rQ(CYO1G0{O&$PQ(CYO1G0{O&%}Q(CYO1G0{O&&bQ08SO<<JdO&'gQ(CYO1G0{O&)]Q(CYO'#JdO&+`Q(CYO1G1aO&+mQ(CYO1G0TO!*fQ^O'#FnOOQO'#KP'#KPOOQO1G1r1G1rO&+wQWO1G1qO&+|Q(CYO,5?TOOOS7+'e7+'eOOOO1G/V1G/VOOQ07b1G4q1G4qO!(SQ7[O7+(]O&,WQWO,5?UO9aQWO,5?UOOQO-E<h-E<hO&,fQWO1G6XO&,fQWO1G6XO&,nQWO1G6XO&,yQ7[O7+'uO&-ZQpO,5?WO&-eQWO,5?WO!&dQ7[O,5?WOOQO-E<j-E<jO&-jQpO1G6YO&-tQWO1G6YOOQ07`1G2e1G2eO$'ZQWO1G2eOOQ07`1G2d1G2dO&-|QWO1G2fO!&dQ7[O1G2fOOQ07`1G2k1G2kO!@}Q`O1G2dOC_QWO1G2eO&.RQWO1G2fO&.ZQWO1G2eO&.}Q7[O,5?YOOQ07b-E<m-E<mO&/pQ7[O,5?[OOQ07b-E<o-E<oO!(SQ7[O7++TOOQ07b1G/_1G/_O&/zQWO1G/_OOQ07b7+'p7+'pO&0PQ7[O7+'wO&0aQ08SO<<KTOOQ07b<<KT<<KTO&1TQWO1G0vO!&dQ7[O'#IsO&1YQWO,5@oO!&dQ7[O1G2iOOQU<<Gz<<GzO!@rQ07hO<<GzO&1bQ08SO<<IwOOQ07b<<Iw<<IwOOQO,5?e,5?eO&2UQWO,5?eO&2ZQWO,5?eOOQO-E<w-E<wO&2iQWO1G6bO&2iQWO1G6bO9aQWO1G6bO@bQWO<<LfOOQU<<Lf<<LfO&2qQWO<<LfO9kQ07hO<<LfOOQU<<LR<<LRO%2{Q08QO<<LROOQU<<LS<<LSO%3VQpO<<LSO&2vQ`O'#IuO&3RQWO,5@sO!*fQ^O,5@sOOQU1G3Q1G3QO&3ZQ^O'#JmOOQO'#Iw'#IwO9kQ07hO'#IwO&3eQ`O,5=oOOQU,5=o,5=oO&3lQ`O'#EcO&4QQWO7+(tO&4VQWO7+(tOOQU7+(t7+(tO!&dQ7[O7+(tO%[Q^O7+(tO&4_QWO7+(tOOQU7+(v7+(vO9kQ07hO7+(vO$![QWO7+(vO9UQWO7+(vO!@}Q`O7+(vO&4jQWO,5?dOOQO-E<v-E<vOOQO'#HW'#HWO&4uQWO1G6`O9kQ07hO<<GpOOQU<<Gp<<GpO@bQWO<<GpO&4}QWO7++}O&5SQWO7+,OO%[Q^O7++}O%[Q^O7+,OOOQU7+)O7+)OO&5XQWO7+)OO&5^Q^O7+)OO&5eQWO7+)OOOQU<<Lr<<LrOOQU<<Lt<<LtOOQU-E<y-E<yOOQU1G3s1G3sO&5jQWO,5>YOOQU,5>[,5>[O&5oQWO1G3yO9ZQWO7+&bO!*fQ^O7+&bOOQO7+%[7+%[O&5tQ(CYO1G6PO>pQWO7+%[OOQ07b<<I`<<I`OOQ07b<<Iv<<IvO>pQWO<<IvOOQO<<Io<<IoO$=mQ08SO<<IoO%[Q^O<<IoOOQO<<Ic<<IcO!@rQ07hO<<IcO&6OQ07hO<<IoO&6ZQ08SO<= SO&6kQWO<= ROOQO7+*W7+*WO9ZQWO7+*WOOQUANAeANAeO&6sQWOANAeO!&dQ7[OANAeO#%sQWOANAeO%0oQrOANAeO%[Q^OANAeO&6{Q08SO7+'uO&9^Q08SO,5?YO&;iQ08SO,5?[O&=tQ08SO7+'wO&@VQrO1G4fO&@aQ(CYO7+&]O&BeQ(CYO,5=RO&DlQ(CYO,5=TO&D|Q(CYO,5=RO&E^Q(CYO,5=TO&EnQ(CYO,59qO&GqQ(CYO,5<fO&ItQ(CYO,5<hO&KwQ(CYO,5<vO&MmQ(CYO7+'hO&MzQ(CYO7+'iO&NXQWO,5<YOOQO7+']7+']O&N^Q7[O<<KwOOQO1G4p1G4pO&NeQWO1G4pO&NpQWO1G4pO' OQWO7++sO' OQWO7++sO!&dQ7[O1G4rO' WQpO1G4rO' bQWO7++tOOQ07`7+(P7+(PO$'ZQWO7+(QO' jQpO7+(QOOQ07`7+(O7+(OO$'ZQWO7+(PO' qQWO7+(QO!&dQ7[O7+(QOC_QWO7+(PO' vQ7[O<<NoOOQ07b7+$y7+$yO'!QQpO,5?_OOQO-E<q-E<qO'![Q08QO7+(TOOQUAN=fAN=fO9aQWO1G5POOQO1G5P1G5PO'!lQWO1G5PO'!qQWO7++|O'!qQWO7++|O9kQ07hOANBQO@bQWOANBQOOQUANBQANBQOOQUANAmANAmOOQUANAnANAnO'!yQWO,5?aOOQO-E<s-E<sO'#UQ(CYO1G6_O'%fQrO'#ChOOQO,5?c,5?cOOQO-E<u-E<uOOQU1G3Z1G3ZO&3ZQ^O,5<zOOQU<<L`<<L`O!&dQ7[O<<L`O&4QQWO<<L`O'%pQWO<<L`O%[Q^O<<L`OOQU<<Lb<<LbO9kQ07hO<<LbO$![QWO<<LbO9UQWO<<LbO'%xQ`O1G5OO'&TQWO7++zOOQUAN=[AN=[O9kQ07hOAN=[OOQU<= i<= iOOQU<= j<= jO'&]QWO<= iO'&bQWO<= jOOQU<<Lj<<LjO'&gQWO<<LjO'&lQ^O<<LjOOQU1G3t1G3tO>pQWO7+)eO'&sQWO<<I|O''OQ(CYO<<I|OOQO<<Hv<<HvOOQ07bAN?bAN?bOOQOAN?ZAN?ZO$=mQ08SOAN?ZOOQOAN>}AN>}O%[Q^OAN?ZOOQO<<Mr<<MrOOQUG27PG27PO!&dQ7[OG27PO#%sQWOG27PO''YQWOG27PO%0oQrOG27PO''bQ(CYO<<JdO''oQ(CYO1G2ZO')eQ(CYO,5?YO'+hQ(CYO,5?[O'-kQ(CYO1G2mO'/nQ(CYO1G2oO'1qQ(CYO<<KTO'2OQ(CYO<<IwOOQO1G1t1G1tO!(SQ7[OANAcOOQO7+*[7+*[O'2]QWO7+*[O'2hQWO<= _O'2pQpO7+*^OOQ07`<<Kl<<KlO$'ZQWO<<KlOOQ07`<<Kk<<KkO'2zQpO<<KlO$'ZQWO<<KkOOQO7+*k7+*kO9aQWO7+*kO'3RQWO<= hOOQUG27lG27lO9kQ07hOG27lO!*fQ^O1G4{O'3ZQWO7++yO&4QQWOANAzOOQUANAzANAzO!&dQ7[OANAzO'3cQWOANAzOOQUANA|ANA|O9kQ07hOANA|O$![QWOANA|OOQO'#HX'#HXOOQO7+*j7+*jOOQUG22vG22vOOQUANETANETOOQUANEUANEUOOQUANBUANBUO'3kQWOANBUOOQU<<MP<<MPO!*fQ^OAN?hOOQOG24uG24uO$=mQ08SOG24uO#%sQWOLD,kOOQULD,kLD,kO!&dQ7[OLD,kO'3pQWOLD,kO'3xQ(CYO7+'uO'5nQ(CYO,5?YO'7qQ(CYO,5?[O'9tQ(CYO7+'wO';jQ7[OG26}OOQO<<Mv<<MvOOQ07`ANAWANAWO$'ZQWOANAWOOQ07`ANAVANAVOOQO<<NV<<NVOOQULD-WLD-WO';zQ(CYO7+*gOOQUG27fG27fO&4QQWOG27fO!&dQ7[OG27fOOQUG27hG27hO9kQ07hOG27hOOQUG27pG27pO'<UQ(CYOG25SOOQOLD*aLD*aOOQU!$(!V!$(!VO#%sQWO!$(!VO!&dQ7[O!$(!VO'<`Q08SOG26}OOQ07`G26rG26rOOQULD-QLD-QO&4QQWOLD-QOOQULD-SLD-SOOQU!)9Eq!)9EqO#%sQWO!)9EqOOQU!$(!l!$(!lOOQU!.K;]!.K;]O'>qQ(CYOG26}O!*fQ^O'#DyO1PQWO'#EWO'@gQrO'#JiO!*fQ^O'#DqO'@nQ^O'#D}O'@uQrO'#ChO'C]QrO'#ChO!*fQ^O'#EPO'CmQ^O,5;VO!*fQ^O,5;aO!*fQ^O,5;aO!*fQ^O,5;aO!*fQ^O,5;aO!*fQ^O,5;aO!*fQ^O,5;aO!*fQ^O,5;aO!*fQ^O,5;aO!*fQ^O,5;aO!*fQ^O,5;aO!*fQ^O,5;aO!*fQ^O'#IiO'EpQWO,5<eO'ExQ7[O,5;aO'GcQ7[O,5;aO!*fQ^O,5;uO!&dQ7[O'#GgO'ExQ7[O'#GgO!&dQ7[O'#GiO'ExQ7[O'#GiO1SQWO'#DVO1SQWO'#DVO!&dQ7[O'#FzO'ExQ7[O'#FzO!&dQ7[O'#F|O'ExQ7[O'#F|O!&dQ7[O'#G[O'ExQ7[O'#G[O!*fQ^O,5:iO!*fQ^O,5@eO'CmQ^O1G0qO'GjQ(CYO'#ChO!*fQ^O1G1|O!&dQ7[O'#InO'ExQ7[O'#InO!&dQ7[O'#IpO'ExQ7[O'#IpO!&dQ7[O,5<oO'ExQ7[O,5<oO'CmQ^O1G1}O!*fQ^O7+&xO!&dQ7[O1G2ZO'ExQ7[O1G2ZO!&dQ7[O'#InO'ExQ7[O'#InO!&dQ7[O'#IpO'ExQ7[O'#IpO!&dQ7[O1G2]O'ExQ7[O1G2]O'CmQ^O7+'iO'CmQ^O7+&]O!&dQ7[OANAcO'ExQ7[OANAcO'GtQWO'#EkO'GyQWO'#EkO'HRQWO'#FZO'HWQWO'#EuO'H]QWO'#JyO'HhQWO'#JwO'HsQWO,5;VO'HxQ7[O,5<bO'IPQWO'#GTO'IUQWO'#GTO'IZQWO,5<cO'IcQWO,5;VO'IkQ(CYO1G1^O'IrQWO,5<oO'IwQWO,5<oO'I|QWO,5<qO'JRQWO,5<qO'JWQWO1G1}O'J]QWO1G0qO'JbQ7[O<<KwO'JiQ7[O<<KwO7hQ7[O'#FxO9UQWO'#FwOA]QWO'#EjO!*fQ^O,5;rO!3fQWO'#GTO!3fQWO'#GTO!3fQWO'#GVO!3fQWO'#GVO!(SQ7[O7+(]O!(SQ7[O7+(]O%*yQpO1G2qO%*yQpO1G2qO!&dQ7[O,5=VO!&dQ7[O,5=V",stateData:"'Km~O'tOS'uOSSOS'vRQ~OPYOQYORfOX!VO`qOczOdyOlkOnYOokOpkOvkOxYOzYO!PWO!TkO!UkO![XO!fuO!kZO!nYO!oYO!pYO!rvO!twO!wxO!{]O#s!PO$T|O%b}O%d!QO%f!OO%g!OO%h!OO%k!RO%m!SO%p!TO%q!TO%s!UO&P!WO&V!XO&X!YO&Z!ZO&]![O&`!]O&f!^O&l!_O&n!`O&p!aO&r!bO&t!cO'{SO'}TO(QUO(XVO(g[O(tiO~OVtO~P`OPYOQYORfOc!jOd!iOlkOnYOokOpkOvkOxYOzYO!PWO!TkO!UkO![!eO!fuO!kZO!nYO!oYO!pYO!rvO!t!gO!w!hO$T!kO'{!dO'}TO(QUO(XVO(g[O(tiO~O`!vOo!nO!P!oO!_!xO!`!uO!a!uO!{:dO#P!pO#Q!pO#R!wO#S!pO#T!pO#W!yO#X!yO'|!lO'}TO(QUO([!mO(g!sO~O'v!zO~OP[XZ[X`[Xn[X|[X}[X!P[X!Y[X!h[X!i[X!k[X!o[X#[[X#geX#j[X#k[X#l[X#m[X#n[X#o[X#p[X#q[X#r[X#t[X#v[X#x[X#y[X$O[X'r[X(X[X(h[X(o[X(p[X~O!d$|X~P(qO^!|O'}#OO(O!|O(P#OO~O^#PO(P#OO(Q#OO(R#PO~Ot#RO!R#SO(Y#SO(Z#UO~OPYOQYORfOc!jOd!iOlkOnYOokOpkOvkOxYOzYO!PWO!TkO!UkO![!eO!fuO!kZO!nYO!oYO!pYO!rvO!t!gO!w!hO$T!kO'{:hO'}TO(QUO(XVO(g[O(tiO~O!X#YO!Y#VO!V(_P!V(lP~P+}O!Z#bO~P`OPYOQYORfOc!jOd!iOnYOokOpkOvkOxYOzYO!PWO!TkO!UkO![!eO!fuO!kZO!nYO!oYO!pYO!rvO!t!gO!w!hO$T!kO'}TO(QUO(XVO(g[O(tiO~Ol#lO!X#hO!{]O#e#kO#f#hO'{:iO!j(iP~P.iO!k#nO'{#mO~O!w#rO!{]O%b#sO~O#g#tO~O!d#uO#g#tO~OP$]OZ$dOn$QO|#yO}#zO!P#{O!Y$aO!h$SO!i#wO!k#xO!o$]O#j$OO#k$PO#l$PO#m$PO#n$RO#o$SO#p$SO#q$cO#r$SO#t$TO#v$VO#x$XO#y$YO(XVO(h$ZO(o#|O(p#}O~O`(]X'r(]X'p(]X!j(]X!V(]X![(]X%c(]X!d(]X~P1qO#[$eO$O$eOP(^XZ(^Xn(^X|(^X}(^X!P(^X!Y(^X!h(^X!k(^X!o(^X#j(^X#k(^X#l(^X#m(^X#n(^X#o(^X#p(^X#q(^X#r(^X#t(^X#v(^X#x(^X#y(^X(X(^X(h(^X(o(^X(p(^X![(^X%c(^X~O`(^X!i(^X'r(^X'p(^X!V(^X!j(^Xr(^X!d(^X~P4XO#[$eO~O$Y$gO$[$fO$c$lO~ORfO![$mO$f$nO$h$pO~Og%VOl%WOn$tOo$sOp$sOv%XOx%YOz%ZO!P${O![$|O!f%`O!k$xO#f%aO$T%^O$o%[O$q%]O$t%_O'{$rO'}TO(QUO(X$uO(o$}O(p%POf(UP~O!k%bO~O!P%eO![%fO'{%dO~O!d%jO~O`%kO'r%kO~O'|!lO~P%[O%h%rO~P%[Og%VO!k%bO'{%dO'|!lO~Od%yO!k%bO'{%dO~O#r$SO~O|&OO![%{O!k%}O%d&RO'{%dO'|!lO'}TO(QUO_(}P~O!w#rO~O%m&TO!P(yX![(yX'{(yX~O'{&UO~O!t&ZO#s!PO%d!QO%f!OO%g!OO%h!OO%k!RO%m!SO%p!TO%q!TO~Oc&`Od&_O!w&]O%b&^O%u&[O~P;xOc&cOdyO![&bO!t&ZO!wxO!{]O#s!PO%b}O%f!OO%g!OO%h!OO%k!RO%m!SO%p!TO%q!TO%s!UO~Oa&fO#[&iO%d&dO'|!lO~P<}O!k&jO!t&nO~O!k#nO~O![XO~O`%kO'q&vO'r%kO~O`%kO'q&yO'r%kO~O`%kO'q&{O'r%kO~O'p[X!V[Xr[X!j[X&T[X![[X%c[X!d[X~P(qO!_'YO!`'RO!a'RO'|!lO'}TO(QUO~Oo'PO!P'OO!X'SO([&}O!Z(`P!Z(nP~P@UOj']O!['ZO'{%dO~Od'bO!k%bO'{%dO~O|&OO!k%}O~Oo!nO!P!oO!{:dO#P!pO#Q!pO#S!pO#T!pO'|!lO'}TO(QUO([!mO(g!sO~O!_'hO!`'gO!a'gO#R!pO#W'iO#X'iO~PApO`%kOg%VO!d#uO!k%bO'r%kO(h'kO~O!o'oO#['mO~PCOOo!nO!P!oO'}TO(QUO([!mO(g!sO~O![XOo(eX!P(eX!_(eX!`(eX!a(eX!{(eX#P(eX#Q(eX#R(eX#S(eX#T(eX#W(eX#X(eX'|(eX'}(eX(Q(eX([(eX(g(eX~O!`'gO!a'gO'|!lO~PCnO'w'sO'x'sO'y'uO~O^!|O'}'wO(O!|O(P'wO~O^#PO(P'wO(Q'wO(R#PO~Ot#RO!R#SO(Y#SO(Z'{O~O!X'}O!V'PX!V'VX!Y'PX!Y'VX~P+}O!Y(PO!V(_X~OP$]OZ$dOn$QO|#yO}#zO!P#{O!Y(PO!h$SO!i#wO!k#xO!o$]O#j$OO#k$PO#l$PO#m$PO#n$RO#o$SO#p$SO#q$cO#r$SO#t$TO#v$VO#x$XO#y$YO(XVO(h$ZO(o#|O(p#}O~O!V(_X~PGbO!V(UO~O!V(kX!Y(kX!d(kX!j(kX(h(kX~O#[(kX#g#`X!Z(kX~PIhO#[(VO!V(mX!Y(mX~O!Y(WO!V(lX~O!V(ZO~O#[$eO~PIhO!Z([O~P`O|#yO}#zO!P#{O!i#wO!k#xO(XVOP!maZ!man!ma!Y!ma!h!ma!o!ma#j!ma#k!ma#l!ma#m!ma#n!ma#o!ma#p!ma#q!ma#r!ma#t!ma#v!ma#x!ma#y!ma(h!ma(o!ma(p!ma~O`!ma'r!ma'p!ma!V!ma!j!mar!ma![!ma%c!ma!d!ma~PKOO!j(]O~O!d#uO#[(^O(h'kO!Y(jX`(jX'r(jX~O!j(jX~PMnO!P%eO![%fO!{]O#e(cO#f(bO'{%dO~O!Y(dO!j(iX~O!j(fO~O!P%eO![%fO#f(bO'{%dO~OP(^XZ(^Xn(^X|(^X}(^X!P(^X!Y(^X!h(^X!i(^X!k(^X!o(^X#j(^X#k(^X#l(^X#m(^X#n(^X#o(^X#p(^X#q(^X#r(^X#t(^X#v(^X#x(^X#y(^X(X(^X(h(^X(o(^X(p(^X~O!d#uO!j(^X~P! [O|(gO}(hO!i#wO!k#xO!{!za!P!za~O!w!za%b!za![!za#e!za#f!za'{!za~P!#`O!w(lO~OPYOQYORfOc!jOd!iOlkOnYOokOpkOvkOxYOzYO!PWO!TkO!UkO![XO!fuO!kZO!nYO!oYO!pYO!rvO!t!gO!w!hO$T!kO'{!dO'}TO(QUO(XVO(g[O(tiO~Og%VOl%WOn$tOo$sOp$sOv%XOx%YOz;QO!P${O![$|O!f<`O!k$xO#f;WO$T%^O$o;SO$q;UO$t%_O'{(pO'}TO(QUO(X$uO(o$}O(p%PO~O#g(rO~Og%VOl%WOn$tOo$sOp$sOv%XOx%YOz%ZO!P${O![$|O!f%`O!k$xO#f%aO$T%^O$o%[O$q%]O$t%_O'{(pO'}TO(QUO(X$uO(o$}O(p%PO~Of(bP~P!(SO!X(vO!j(cP~P%[O([(xO(g[O~O!P(zO!k#xO([(xO(g[O~OP:cOQ:cORfOc<[Od!iOlkOn:cOokOpkOvkOx:cOz:cO!PWO!TkO!UkO![!eO!f:fO!kZO!n:cO!o:cO!p:cO!r:gO!t:jO!w!hO$T!kO'{)YO'}TO(QUO(XVO(g[O(t<YO~O})]O!k#xO~O!Y$aO`$ma'r$ma'p$ma!j$ma!V$ma![$ma%c$ma!d$ma~O#s)aO~P!&dO|)dO!d)cO![$ZX$W$ZX$Y$ZX$[$ZX$c$ZX~O!d)cO![(qX$W(qX$Y(qX$[(qX$c(qX~O|)dO~P!.OO|)dO![(qX$W(qX$Y(qX$[(qX$c(qX~O![)fO$W)jO$Y)eO$[)eO$c)kO~O!X)nO~P!*fO$Y$gO$[$fO$c)rO~Oj$uX|$uX!P$uX!i$uX(o$uX(p$uX~OfiXf$uXjiX!YiX#[iX~P!/tOo)tO~Ot)uO(Y)vO(Z)xO~Oj*RO|)zO!P){O(o$}O(p%PO~Of)yO~P!0}Of*SO~Og%VOl%WOn$tOo$sOp$sOv%XOx%YOz;QO!P${O![$|O!f<`O!k$xO#f;WO$T%^O$o;SO$q;UO$t%_O'}TO(QUO(X$uO(o$}O(p%PO~O!X*WO'{*TO!j(uP~P!1lO#g*YO~O!k*ZO~O!X*`O'{*]O!V(vP~P!1lOn*lO!P*dO!_*jO!`*cO!a*cO!k*ZO#W*kO%Y*fO'|!lO([!mO~O!Z*iO~P!3xO!i#wOj(WX|(WX!P(WX(o(WX(p(WX!Y(WX#[(WX~Of(WX#|(WX~P!4qOj*qO#[*pOf(VX!Y(VX~O!Y*rOf(UX~O'{&UOf(UP~O!k*yO~O'{(pO~Ol*}O!P%eO!X#hO![%fO!{]O#e#kO#f#hO'{%dO!j(iP~O!d#uO#g+OO~O!P%eO!X+QO!Y(WO![%fO'{%dO!V(lP~Oo'VO!P+SO!X+RO'}TO(QUO([(xO~O!Z(nP~P!7lO!Y+TO`(zX'r(zX~OP$]OZ$dOn$QO|#yO}#zO!P#{O!h$SO!i#wO!k#xO!o$]O#j$OO#k$PO#l$PO#m$PO#n$RO#o$SO#p$SO#q$cO#r$SO#t$TO#v$VO#x$XO#y$YO(XVO(h$ZO(o#|O(p#}O~O`!ea!Y!ea'r!ea'p!ea!V!ea!j!ear!ea![!ea%c!ea!d!ea~P!8dO|#yO}#zO!P#{O!i#wO!k#xO(XVOP!qaZ!qan!qa!Y!qa!h!qa!o!qa#j!qa#k!qa#l!qa#m!qa#n!qa#o!qa#p!qa#q!qa#r!qa#t!qa#v!qa#x!qa#y!qa(h!qa(o!qa(p!qa~O`!qa'r!qa'p!qa!V!qa!j!qar!qa![!qa%c!qa!d!qa~P!:}O|#yO}#zO!P#{O!i#wO!k#xO(XVOP!saZ!san!sa!Y!sa!h!sa!o!sa#j!sa#k!sa#l!sa#m!sa#n!sa#o!sa#p!sa#q!sa#r!sa#t!sa#v!sa#x!sa#y!sa(h!sa(o!sa(p!sa~O`!sa'r!sa'p!sa!V!sa!j!sar!sa![!sa%c!sa!d!sa~P!=hOg%VOj+^O!['ZO%c+]O~O!d+`O`(TX![(TX'r(TX!Y(TX~O`%kO![XO'r%kO~Og%VO!k%bO~Og%VO!k%bO'{%dO~O!d#uO#g(rO~Oa+kO%d+lO'{+hO'}TO(QUO!Z)OP~O!Y+mO_(}X~OZ+qO~O_+rO~O![%{O'{%dO'|!lO_(}P~Og%VO#[+wO~Og%VOj+zO![$|O~O![+|O~O|,OO![XO~O%h%rO~O!w,TO~Od,YO~Oa,ZO'{#mO'}TO(QUO!Z(|P~Od%yO~O%d!QO'{&UO~P<}OZ,`O_,_O~OPYOQYORfOczOdyOlkOnYOokOpkOvkOxYOzYO!PWO!TkO!UkO!fuO!kZO!nYO!oYO!pYO!rvO!wxO!{]O%b}O'}TO(QUO(XVO(g[O(tiO~O![!eO!t!gO$T!kO'{!dO~P!DkO_,_O`%kO'r%kO~OPYOQYORfOc!jOd!iOlkOnYOokOpkOvkOxYOzYO!PWO!TkO!UkO![!eO!fuO!kZO!nYO!oYO!pYO!rvO!w!hO$T!kO'{!dO'}TO(QUO(XVO(g[O(tiO~O`,eO!twO#s!OO%f!OO%g!OO%h!OO~P!GTO!k&jO~O&V,kO~O![,mO~O&h,oO&j,pOP&eaQ&eaR&eaX&ea`&eac&ead&eal&ean&eao&eap&eav&eax&eaz&ea!P&ea!T&ea!U&ea![&ea!f&ea!k&ea!n&ea!o&ea!p&ea!r&ea!t&ea!w&ea!{&ea#s&ea$T&ea%b&ea%d&ea%f&ea%g&ea%h&ea%k&ea%m&ea%p&ea%q&ea%s&ea&P&ea&V&ea&X&ea&Z&ea&]&ea&`&ea&f&ea&l&ea&n&ea&p&ea&r&ea&t&ea'p&ea'{&ea'}&ea(Q&ea(X&ea(g&ea(t&ea!Z&ea&^&eaa&ea&c&ea~O'{,uO~Og!bX!Y!OX!Y!bX!Z!OX!Z!bX!d!OX!d!bX!k!bX#[!OX~O!d,zO#[,yOg(aX!Y#dX!Y(aX!Z#dX!Z(aX!d(aX!k(aX~Og%VO!d,|O!k%bO!Y!^X!Z!^X~Oo!nO!P!oO'}TO(QUO([!mO~OP:cOQ:cORfOc<[Od!iOlkOn:cOokOpkOvkOx:cOz:cO!PWO!TkO!UkO![!eO!f:fO!kZO!n:cO!o:cO!p:cO!r:gO!t:jO!w!hO$T!kO'}TO(QUO(XVO(g[O(t<YO~O'{;]O~P#!ZO!Y-QO!Z(`X~O!Z-SO~O!d,zO#[,yO!Y#dX!Z#dX~O!Y-TO!Z(nX~O!Z-VO~O!`-WO!a-WO'|!lO~P# xO!Z-ZO~P'_Oj-^O!['ZO~O!V-cO~Oo!za!_!za!`!za!a!za#P!za#Q!za#R!za#S!za#T!za#W!za#X!za'|!za'}!za(Q!za([!za(g!za~P!#`O!o-hO#[-fO~PCOO!`-jO!a-jO'|!lO~PCnO`%kO#[-fO'r%kO~O`%kO!d#uO#[-fO'r%kO~O`%kO!d#uO!o-hO#[-fO'r%kO(h'kO~O'w'sO'x'sO'y-oO~Or-pO~O!V'Pa!Y'Pa~P!8dO!X-tO!V'PX!Y'PX~P%[O!Y(PO!V(_a~O!V(_a~PGbO!Y(WO!V(la~O!P%eO!X-xO![%fO'{%dO!V'VX!Y'VX~O#[-zO!Y(ja!j(ja`(ja'r(ja~O!d#uO~P#*aO!Y(dO!j(ia~O!P%eO![%fO#f.OO'{%dO~Ol.TO!P%eO!X.QO![%fO!{]O#e.SO#f.QO'{%dO!Y'YX!j'YX~O}.XO!k#xO~Og%VOj.[O!['ZO%c.ZO~O`#_i!Y#_i'r#_i'p#_i!V#_i!j#_ir#_i![#_i%c#_i!d#_i~P!8dOj<fO|)zO!P){O(o$}O(p%PO~O#g#Za`#Za#[#Za'r#Za!Y#Za!j#Za![#Za!V#Za~P#-]O#g(WXP(WXZ(WX`(WXn(WX}(WX!h(WX!k(WX!o(WX#j(WX#k(WX#l(WX#m(WX#n(WX#o(WX#p(WX#q(WX#r(WX#t(WX#v(WX#x(WX#y(WX'r(WX(X(WX(h(WX!j(WX!V(WX'p(WXr(WX![(WX%c(WX!d(WX~P!4qO!Y.iOf(bX~P!0}Of.kO~O!Y.lO!j(cX~P!8dO!j.oO~O!V.qO~OP$]O|#yO}#zO!P#{O!i#wO!k#xO!o$]O(XVOZ#ii`#iin#ii!Y#ii!h#ii#k#ii#l#ii#m#ii#n#ii#o#ii#p#ii#q#ii#r#ii#t#ii#v#ii#x#ii#y#ii'r#ii(h#ii(o#ii(p#ii'p#ii!V#ii!j#iir#ii![#ii%c#ii!d#ii~O#j#ii~P#1XO#j$OO~P#1XOP$]O|#yO}#zO!P#{O!i#wO!k#xO!o$]O#j$OO#k$PO#l$PO#m$PO(XVOZ#ii`#ii!Y#ii!h#ii#n#ii#o#ii#p#ii#q#ii#r#ii#t#ii#v#ii#x#ii#y#ii'r#ii(h#ii(o#ii(p#ii'p#ii!V#ii!j#iir#ii![#ii%c#ii!d#ii~On#ii~P#3yOn$QO~P#3yOP$]On$QO|#yO}#zO!P#{O!i#wO!k#xO!o$]O#j$OO#k$PO#l$PO#m$PO#n$RO(XVO`#ii!Y#ii#t#ii#v#ii#x#ii#y#ii'r#ii(h#ii(o#ii(p#ii'p#ii!V#ii!j#iir#ii![#ii%c#ii!d#ii~OZ#ii!h#ii#o#ii#p#ii#q#ii#r#ii~P#6kOZ$dO!h$SO#o$SO#p$SO#q$cO#r$SO~P#6kOP$]OZ$dOn$QO|#yO}#zO!P#{O!h$SO!i#wO!k#xO!o$]O#j$OO#k$PO#l$PO#m$PO#n$RO#o$SO#p$SO#q$cO#r$SO#t$TO(XVO(p#}O`#ii!Y#ii#x#ii#y#ii'r#ii(h#ii(o#ii'p#ii!V#ii!j#iir#ii![#ii%c#ii!d#ii~O#v$VO~P#9lO#v#ii~P#9lOP$]OZ$dOn$QO|#yO}#zO!P#{O!h$SO!i#wO!k#xO!o$]O#j$OO#k$PO#l$PO#m$PO#n$RO#o$SO#p$SO#q$cO#r$SO#t$TO(XVO`#ii!Y#ii#x#ii#y#ii'r#ii(h#ii'p#ii!V#ii!j#iir#ii![#ii%c#ii!d#ii~O#v#ii(o#ii(p#ii~P#<^O#v$VO(o#|O(p#}O~P#<^OP$]OZ$dOn$QO|#yO}#zO!P#{O!h$SO!i#wO!k#xO!o$]O#j$OO#k$PO#l$PO#m$PO#n$RO#o$SO#p$SO#q$cO#r$SO#t$TO#v$VO#x$XO(XVO(o#|O(p#}O~O`#ii!Y#ii#y#ii'r#ii(h#ii'p#ii!V#ii!j#iir#ii![#ii%c#ii!d#ii~P#?UOP[XZ[Xn[X|[X}[X!P[X!h[X!i[X!k[X!o[X#[[X#geX#j[X#k[X#l[X#m[X#n[X#o[X#p[X#q[X#r[X#t[X#v[X#x[X#y[X$O[X(X[X(h[X(o[X(p[X!Y[X!Z[X~O#|[X~P#AoOP$]OZ:zOn:nO|#yO}#zO!P#{O!h:pO!i#wO!k#xO!o$]O#j:lO#k:mO#l:mO#m:mO#n:oO#o:pO#p:pO#q:yO#r:pO#t:qO#v:sO#x:uO#y:vO(XVO(h$ZO(o#|O(p#}O~O#|.sO~P#C|O#[:{O$O:{O#|(^X!Z(^X~P! [O`']a!Y']a'r']a'p']a!j']a!V']ar']a![']a%c']a!d']a~P!8dOP#iiZ#ii`#iin#ii}#ii!Y#ii!h#ii!i#ii!k#ii!o#ii#j#ii#k#ii#l#ii#m#ii#n#ii#o#ii#p#ii#q#ii#r#ii#t#ii#v#ii#x#ii#y#ii'r#ii(X#ii(h#ii'p#ii!V#ii!j#iir#ii![#ii%c#ii!d#ii~P#-]O`#}i!Y#}i'r#}i'p#}i!V#}i!j#}ir#}i![#}i%c#}i!d#}i~P!8dO$Y.xO$[.xO~O$Y.yO$[.yO~O!d)cO#[.zO![$`X$W$`X$Y$`X$[$`X$c$`X~O!X.{O~O![)fO$W.}O$Y)eO$[)eO$c/OO~O!Y:wO!Z(]X~P#C|O!Z/PO~O!d)cO$c(qX~O$c/RO~Ot)uO(Y)vO(Z/UO~O!V/YO~P!&dO(o$}Oj%Za|%Za!P%Za(p%Za!Y%Za#[%Za~Of%Za#|%Za~P#L^O(p%POj%]a|%]a!P%]a(o%]a!Y%]a#[%]a~Of%]a#|%]a~P#MPO!YeX!deX!jeX!j$uX(heX~P!/tO!j/bO~P#-]O!Y/cO!d#uO(h'kO!j(uX~O!j/hO~O!X*WO'{%dO!j(uP~O#g/jO~O!V$uX!Y$uX!d$|X~P!/tO!Y/kO!V(vX~P#-]O!d/mO~O!V/oO~Og%VOn/sO!d#uO!k%bO(h'kO~O'{/uO~O!d+`O~O`%kO!Y/yO'r%kO~O!Z/{O~P!3xO!`/|O!a/|O'|!lO([!mO~O!P0OO([!mO~O#W0PO~Of%Za!Y%Za#[%Za#|%Za~P!0}Of%]a!Y%]a#[%]a#|%]a~P!0}O'{&UOf'fX!Y'fX~O!Y*rOf(Ua~Of0YO~O|0ZO}0ZO!P0[Ojya(oya(pya!Yya#[ya~Ofya#|ya~P$$jO|)zO!P){Oj$na(o$na(p$na!Y$na#[$na~Of$na#|$na~P$%`O|)zO!P){Oj$pa(o$pa(p$pa!Y$pa#[$pa~Of$pa#|$pa~P$&RO#g0^O~Of%Oa!Y%Oa#[%Oa#|%Oa~P!0}O!d#uO~O#g0aO~O!Y+TO`(za'r(za~O|#yO}#zO!P#{O!i#wO!k#xO(XVOP!qiZ!qin!qi!Y!qi!h!qi!o!qi#j!qi#k!qi#l!qi#m!qi#n!qi#o!qi#p!qi#q!qi#r!qi#t!qi#v!qi#x!qi#y!qi(h!qi(o!qi(p!qi~O`!qi'r!qi'p!qi!V!qi!j!qir!qi![!qi%c!qi!d!qi~P$'pOg%VOn$tOo$sOp$sOv%XOx%YOz;QO!P${O![$|O!f<`O!k$xO#f;WO$T%^O$o;SO$q;UO$t%_O'}TO(QUO(X$uO(o$}O(p%PO~Ol0kO'{0jO~P$*ZO!d+`O`(Ta![(Ta'r(Ta!Y(Ta~O#g0qO~OZ[X!YeX!ZeX~O!Y0rO!Z)OX~O!Z0tO~OZ0uO~Oa0wO'{+hO'}TO(QUO~O![%{O'{%dO_'nX!Y'nX~O!Y+mO_(}a~O!j0zO~P!8dOZ0}O~O_1OO~O#[1RO~Oj1UO![$|O~O([(xO!Z({P~Og%VOj1_O![1[O%c1^O~OZ1iO!Y1gO!Z(|X~O!Z1jO~O_1lO`%kO'r%kO~O'{#mO'}TO(QUO~O#[$eO$O$eOP(^XZ(^Xn(^X|(^X}(^X!P(^X!Y(^X!h(^X!k(^X!o(^X#j(^X#k(^X#l(^X#m(^X#n(^X#o(^X#p(^X#q(^X#t(^X#v(^X#x(^X#y(^X(X(^X(h(^X(o(^X(p(^X~O#r1oO&T1pO`(^X!i(^X~P$/qO#[$eO#r1oO&T1pO~O`1rO~P%[O`1tO~O&^1wOP&[iQ&[iR&[iX&[i`&[ic&[id&[il&[in&[io&[ip&[iv&[ix&[iz&[i!P&[i!T&[i!U&[i![&[i!f&[i!k&[i!n&[i!o&[i!p&[i!r&[i!t&[i!w&[i!{&[i#s&[i$T&[i%b&[i%d&[i%f&[i%g&[i%h&[i%k&[i%m&[i%p&[i%q&[i%s&[i&P&[i&V&[i&X&[i&Z&[i&]&[i&`&[i&f&[i&l&[i&n&[i&p&[i&r&[i&t&[i'p&[i'{&[i'}&[i(Q&[i(X&[i(g&[i(t&[i!Z&[ia&[i&c&[i~Oa1}O!Z1{O&c1|O~P`O![XO!k2PO~O&j,pOP&eiQ&eiR&eiX&ei`&eic&eid&eil&ein&eio&eip&eiv&eix&eiz&ei!P&ei!T&ei!U&ei![&ei!f&ei!k&ei!n&ei!o&ei!p&ei!r&ei!t&ei!w&ei!{&ei#s&ei$T&ei%b&ei%d&ei%f&ei%g&ei%h&ei%k&ei%m&ei%p&ei%q&ei%s&ei&P&ei&V&ei&X&ei&Z&ei&]&ei&`&ei&f&ei&l&ei&n&ei&p&ei&r&ei&t&ei'p&ei'{&ei'}&ei(Q&ei(X&ei(g&ei(t&ei!Z&ei&^&eia&ei&c&ei~O!V2VO~O!Y!^a!Z!^a~P#C|Oo!nO!P!oO!X2]O([!mO!Y'QX!Z'QX~P@UO!Y-QO!Z(`a~O!Y'WX!Z'WX~P!7lO!Y-TO!Z(na~O!Z2dO~P'_O`%kO#[2mO'r%kO~O`%kO!d#uO#[2mO'r%kO~O`%kO!d#uO!o2qO#[2mO'r%kO(h'kO~O`%kO'r%kO~P!8dO!Y$aOr$ma~O!V'Pi!Y'Pi~P!8dO!Y(PO!V(_i~O!Y(WO!V(li~O!V(mi!Y(mi~P!8dO!Y(ji!j(ji`(ji'r(ji~P!8dO#[2sO!Y(ji!j(ji`(ji'r(ji~O!Y(dO!j(ii~O!P%eO![%fO!{]O#e2xO#f2wO'{%dO~O!P%eO![%fO#f2wO'{%dO~Oj3PO!['ZO%c3OO~Og%VOj3PO!['ZO%c3OO~O#g%ZaP%ZaZ%Za`%Zan%Za}%Za!h%Za!i%Za!k%Za!o%Za#j%Za#k%Za#l%Za#m%Za#n%Za#o%Za#p%Za#q%Za#r%Za#t%Za#v%Za#x%Za#y%Za'r%Za(X%Za(h%Za!j%Za!V%Za'p%Zar%Za![%Za%c%Za!d%Za~P#L^O#g%]aP%]aZ%]a`%]an%]a}%]a!h%]a!i%]a!k%]a!o%]a#j%]a#k%]a#l%]a#m%]a#n%]a#o%]a#p%]a#q%]a#r%]a#t%]a#v%]a#x%]a#y%]a'r%]a(X%]a(h%]a!j%]a!V%]a'p%]ar%]a![%]a%c%]a!d%]a~P#MPO#g%ZaP%ZaZ%Za`%Zan%Za}%Za!Y%Za!h%Za!i%Za!k%Za!o%Za#j%Za#k%Za#l%Za#m%Za#n%Za#o%Za#p%Za#q%Za#r%Za#t%Za#v%Za#x%Za#y%Za'r%Za(X%Za(h%Za!j%Za!V%Za'p%Za#[%Zar%Za![%Za%c%Za!d%Za~P#-]O#g%]aP%]aZ%]a`%]an%]a}%]a!Y%]a!h%]a!i%]a!k%]a!o%]a#j%]a#k%]a#l%]a#m%]a#n%]a#o%]a#p%]a#q%]a#r%]a#t%]a#v%]a#x%]a#y%]a'r%]a(X%]a(h%]a!j%]a!V%]a'p%]a#[%]ar%]a![%]a%c%]a!d%]a~P#-]O#gyaPyaZya`yanya!hya!iya!kya!oya#jya#kya#lya#mya#nya#oya#pya#qya#rya#tya#vya#xya#yya'rya(Xya(hya!jya!Vya'pyarya![ya%cya!dya~P$$jO#g$naP$naZ$na`$nan$na}$na!h$na!i$na!k$na!o$na#j$na#k$na#l$na#m$na#n$na#o$na#p$na#q$na#r$na#t$na#v$na#x$na#y$na'r$na(X$na(h$na!j$na!V$na'p$nar$na![$na%c$na!d$na~P$%`O#g$paP$paZ$pa`$pan$pa}$pa!h$pa!i$pa!k$pa!o$pa#j$pa#k$pa#l$pa#m$pa#n$pa#o$pa#p$pa#q$pa#r$pa#t$pa#v$pa#x$pa#y$pa'r$pa(X$pa(h$pa!j$pa!V$pa'p$par$pa![$pa%c$pa!d$pa~P$&RO#g%OaP%OaZ%Oa`%Oan%Oa}%Oa!Y%Oa!h%Oa!i%Oa!k%Oa!o%Oa#j%Oa#k%Oa#l%Oa#m%Oa#n%Oa#o%Oa#p%Oa#q%Oa#r%Oa#t%Oa#v%Oa#x%Oa#y%Oa'r%Oa(X%Oa(h%Oa!j%Oa!V%Oa'p%Oa#[%Oar%Oa![%Oa%c%Oa!d%Oa~P#-]O`#_q!Y#_q'r#_q'p#_q!V#_q!j#_qr#_q![#_q%c#_q!d#_q~P!8dOf'RX!Y'RX~P!(SO!Y.iOf(ba~O!X3ZO!Y'SX!j'SX~P%[O!Y.lO!j(ca~O!Y.lO!j(ca~P!8dO!V3^O~O#|!ma!Z!ma~PKOO#|!ea!Y!ea!Z!ea~P#C|O#|!qa!Z!qa~P!:}O#|!sa!Z!sa~P!=hORfO![3pO$a3qO~O!Z3uO~Or3vO~P#-]O`$jq!Y$jq'r$jq'p$jq!V$jq!j$jqr$jq![$jq%c$jq!d$jq~P!8dO!V3wO~P#-]O|)zO!P){O(p%POj'ba(o'ba!Y'ba#['ba~Of'ba#|'ba~P%)eO|)zO!P){Oj'da(o'da(p'da!Y'da#['da~Of'da#|'da~P%*WO(h$ZO~P#-]O!X3zO'{%dO!Y'^X!j'^X~O!Y/cO!j(ua~O!Y/cO!d#uO!j(ua~O!Y/cO!d#uO(h'kO!j(ua~Of$wi!Y$wi#[$wi#|$wi~P!0}O!X4SO'{*]O!V'`X!Y'`X~P!1lO!Y/kO!V(va~O!Y/kO!V(va~P#-]O!d#uO#r4[O~On4_O!d#uO(h'kO~O(o$}Oj%Zi|%Zi!P%Zi(p%Zi!Y%Zi#[%Zi~Of%Zi#|%Zi~P%-jO(p%POj%]i|%]i!P%]i(o%]i!Y%]i#[%]i~Of%]i#|%]i~P%.]Of(Vi!Y(Vi~P!0}O#[4fOf(Vi!Y(Vi~P!0}O!j4iO~O`$kq!Y$kq'r$kq'p$kq!V$kq!j$kqr$kq![$kq%c$kq!d$kq~P!8dO!V4mO~O!Y4nO![(wX~P#-]O!i#wO~P4XO`$uX![$uX%W[X'r$uX!Y$uX~P!/tO%W4pO`kXjkX|kX!PkX![kX'rkX(okX(pkX!YkX~O%W4pO~Oa4vO%d4wO'{+hO'}TO(QUO!Y'mX!Z'mX~O!Y0rO!Z)Oa~OZ4{O~O_4|O~O`%kO'r%kO~P#-]O![$|O~P#-]O!Y5UO#[5WO!Z({X~O!Z5XO~Oo!nO!P5YO!_!xO!`!uO!a!uO!{:dO#P!pO#Q!pO#R!pO#S!pO#T!pO#W5_O#X!yO'|!lO'}TO(QUO([!mO(g!sO~O!Z5^O~P%3nOj5dO![1[O%c5cO~Og%VOj5dO![1[O%c5cO~Oa5kO'{#mO'}TO(QUO!Y'lX!Z'lX~O!Y1gO!Z(|a~O'}TO(QUO([5mO~O_5qO~O#r5tO&T5uO~PMnO!j5vO~P%[O`5xO~O`5xO~P%[Oa1}O!Z5}O&c1|O~P`O!d6PO~O!d6ROg(ai!Y(ai!Z(ai!d(ai!k(ai~O!Y#di!Z#di~P#C|O#[6SO!Y#di!Z#di~O!Y!^i!Z!^i~P#C|O`%kO#[6]O'r%kO~O`%kO!d#uO#[6]O'r%kO~O!Y(jq!j(jq`(jq'r(jq~P!8dO!Y(dO!j(iq~O!P%eO![%fO#f6dO'{%dO~O!['ZO%c6gO~Oj6jO!['ZO%c6gO~O#g'baP'baZ'ba`'ban'ba}'ba!h'ba!i'ba!k'ba!o'ba#j'ba#k'ba#l'ba#m'ba#n'ba#o'ba#p'ba#q'ba#r'ba#t'ba#v'ba#x'ba#y'ba'r'ba(X'ba(h'ba!j'ba!V'ba'p'bar'ba!['ba%c'ba!d'ba~P%)eO#g'daP'daZ'da`'dan'da}'da!h'da!i'da!k'da!o'da#j'da#k'da#l'da#m'da#n'da#o'da#p'da#q'da#r'da#t'da#v'da#x'da#y'da'r'da(X'da(h'da!j'da!V'da'p'dar'da!['da%c'da!d'da~P%*WO#g$wiP$wiZ$wi`$win$wi}$wi!Y$wi!h$wi!i$wi!k$wi!o$wi#j$wi#k$wi#l$wi#m$wi#n$wi#o$wi#p$wi#q$wi#r$wi#t$wi#v$wi#x$wi#y$wi'r$wi(X$wi(h$wi!j$wi!V$wi'p$wi#[$wir$wi![$wi%c$wi!d$wi~P#-]O#g%ZiP%ZiZ%Zi`%Zin%Zi}%Zi!h%Zi!i%Zi!k%Zi!o%Zi#j%Zi#k%Zi#l%Zi#m%Zi#n%Zi#o%Zi#p%Zi#q%Zi#r%Zi#t%Zi#v%Zi#x%Zi#y%Zi'r%Zi(X%Zi(h%Zi!j%Zi!V%Zi'p%Zir%Zi![%Zi%c%Zi!d%Zi~P%-jO#g%]iP%]iZ%]i`%]in%]i}%]i!h%]i!i%]i!k%]i!o%]i#j%]i#k%]i#l%]i#m%]i#n%]i#o%]i#p%]i#q%]i#r%]i#t%]i#v%]i#x%]i#y%]i'r%]i(X%]i(h%]i!j%]i!V%]i'p%]ir%]i![%]i%c%]i!d%]i~P%.]Of'Ra!Y'Ra~P!0}O!Y'Sa!j'Sa~P!8dO!Y.lO!j(ci~O#|#_i!Y#_i!Z#_i~P#C|OP$]O|#yO}#zO!P#{O!i#wO!k#xO!o$]O(XVOZ#iin#ii!h#ii#k#ii#l#ii#m#ii#n#ii#o#ii#p#ii#q#ii#r#ii#t#ii#v#ii#x#ii#y#ii#|#ii(h#ii(o#ii(p#ii!Y#ii!Z#ii~O#j#ii~P%FnO#j:lO~P%FnOP$]O|#yO}#zO!P#{O!i#wO!k#xO!o$]O#j:lO#k:mO#l:mO#m:mO(XVOZ#ii!h#ii#n#ii#o#ii#p#ii#q#ii#r#ii#t#ii#v#ii#x#ii#y#ii#|#ii(h#ii(o#ii(p#ii!Y#ii!Z#ii~On#ii~P%HyOn:nO~P%HyOP$]On:nO|#yO}#zO!P#{O!i#wO!k#xO!o$]O#j:lO#k:mO#l:mO#m:mO#n:oO(XVO#t#ii#v#ii#x#ii#y#ii#|#ii(h#ii(o#ii(p#ii!Y#ii!Z#ii~OZ#ii!h#ii#o#ii#p#ii#q#ii#r#ii~P%KUOZ:zO!h:pO#o:pO#p:pO#q:yO#r:pO~P%KUOP$]OZ:zOn:nO|#yO}#zO!P#{O!h:pO!i#wO!k#xO!o$]O#j:lO#k:mO#l:mO#m:mO#n:oO#o:pO#p:pO#q:yO#r:pO#t:qO(XVO(p#}O#x#ii#y#ii#|#ii(h#ii(o#ii!Y#ii!Z#ii~O#v:sO~P%MpO#v#ii~P%MpOP$]OZ:zOn:nO|#yO}#zO!P#{O!h:pO!i#wO!k#xO!o$]O#j:lO#k:mO#l:mO#m:mO#n:oO#o:pO#p:pO#q:yO#r:pO#t:qO(XVO#x#ii#y#ii#|#ii(h#ii!Y#ii!Z#ii~O#v#ii(o#ii(p#ii~P& {O#v:sO(o#|O(p#}O~P& {OP$]OZ:zOn:nO|#yO}#zO!P#{O!h:pO!i#wO!k#xO!o$]O#j:lO#k:mO#l:mO#m:mO#n:oO#o:pO#p:pO#q:yO#r:pO#t:qO#v:sO#x:uO(XVO(o#|O(p#}O~O#y#ii#|#ii(h#ii!Y#ii!Z#ii~P&$^O`#zy!Y#zy'r#zy'p#zy!V#zy!j#zyr#zy![#zy%c#zy!d#zy~P!8dOj<gO|)zO!P){O(o$}O(p%PO~OP#iiZ#iin#ii}#ii!h#ii!i#ii!k#ii!o#ii#j#ii#k#ii#l#ii#m#ii#n#ii#o#ii#p#ii#q#ii#r#ii#t#ii#v#ii#x#ii#y#ii#|#ii(X#ii(h#ii!Y#ii!Z#ii~P&'UO!i#wOP(WXZ(WXj(WXn(WX|(WX}(WX!P(WX!h(WX!k(WX!o(WX#j(WX#k(WX#l(WX#m(WX#n(WX#o(WX#p(WX#q(WX#r(WX#t(WX#v(WX#x(WX#y(WX#|(WX(X(WX(h(WX(o(WX(p(WX!Y(WX!Z(WX~O#|#}i!Y#}i!Z#}i~P#C|O#|!qi!Z!qi~P$'pO!Z6|O~O!Y']a!Z']a~P#C|O!d#uO(h'kO!Y'^a!j'^a~O!Y/cO!j(ui~O!Y/cO!d#uO!j(ui~Of$wq!Y$wq#[$wq#|$wq~P!0}O!V'`a!Y'`a~P#-]O!d7TO~O!Y/kO!V(vi~P#-]O!Y/kO!V(vi~O!V7XO~O!d#uO#r7^O~On7_O!d#uO(h'kO~O|)zO!P){O(p%POj'ca(o'ca!Y'ca#['ca~Of'ca#|'ca~P&.fO|)zO!P){Oj'ea(o'ea(p'ea!Y'ea#['ea~Of'ea#|'ea~P&/XO!V7aO~Of$yq!Y$yq#[$yq#|$yq~P!0}O`$ky!Y$ky'r$ky'p$ky!V$ky!j$kyr$ky![$ky%c$ky!d$ky~P!8dO!d6RO~O!Y4nO![(wa~O`#_y!Y#_y'r#_y'p#_y!V#_y!j#_yr#_y![#_y%c#_y!d#_y~P!8dOZ7fO~Oa7hO'{+hO'}TO(QUO~O!Y0rO!Z)Oi~O_7lO~O([(xO!Y'iX!Z'iX~O!Y5UO!Z({a~OlkO'{7sO~P.iO!Z7vO~P%3nOo!nO!P7wO'}TO(QUO([!mO(g!sO~O![1[O~O![1[O%c7yO~Oj7|O![1[O%c7yO~OZ8RO!Y'la!Z'la~O!Y1gO!Z(|i~O!j8VO~O!j8WO~O!j8ZO~O!j8ZO~P%[O`8]O~O!d8^O~O!j8_O~O!Y(mi!Z(mi~P#C|O`%kO#[8gO'r%kO~O!Y(jy!j(jy`(jy'r(jy~P!8dO!Y(dO!j(iy~O!['ZO%c8jO~O#g$wqP$wqZ$wq`$wqn$wq}$wq!Y$wq!h$wq!i$wq!k$wq!o$wq#j$wq#k$wq#l$wq#m$wq#n$wq#o$wq#p$wq#q$wq#r$wq#t$wq#v$wq#x$wq#y$wq'r$wq(X$wq(h$wq!j$wq!V$wq'p$wq#[$wqr$wq![$wq%c$wq!d$wq~P#-]O#g'caP'caZ'ca`'can'ca}'ca!h'ca!i'ca!k'ca!o'ca#j'ca#k'ca#l'ca#m'ca#n'ca#o'ca#p'ca#q'ca#r'ca#t'ca#v'ca#x'ca#y'ca'r'ca(X'ca(h'ca!j'ca!V'ca'p'car'ca!['ca%c'ca!d'ca~P&.fO#g'eaP'eaZ'ea`'ean'ea}'ea!h'ea!i'ea!k'ea!o'ea#j'ea#k'ea#l'ea#m'ea#n'ea#o'ea#p'ea#q'ea#r'ea#t'ea#v'ea#x'ea#y'ea'r'ea(X'ea(h'ea!j'ea!V'ea'p'ear'ea!['ea%c'ea!d'ea~P&/XO#g$yqP$yqZ$yq`$yqn$yq}$yq!Y$yq!h$yq!i$yq!k$yq!o$yq#j$yq#k$yq#l$yq#m$yq#n$yq#o$yq#p$yq#q$yq#r$yq#t$yq#v$yq#x$yq#y$yq'r$yq(X$yq(h$yq!j$yq!V$yq'p$yq#[$yqr$yq![$yq%c$yq!d$yq~P#-]O!Y'Si!j'Si~P!8dO#|#_q!Y#_q!Z#_q~P#C|O(o$}OP%ZaZ%Zan%Za}%Za!h%Za!i%Za!k%Za!o%Za#j%Za#k%Za#l%Za#m%Za#n%Za#o%Za#p%Za#q%Za#r%Za#t%Za#v%Za#x%Za#y%Za#|%Za(X%Za(h%Za!Y%Za!Z%Za~Oj%Za|%Za!P%Za(p%Za~P&@nO(p%POP%]aZ%]an%]a}%]a!h%]a!i%]a!k%]a!o%]a#j%]a#k%]a#l%]a#m%]a#n%]a#o%]a#p%]a#q%]a#r%]a#t%]a#v%]a#x%]a#y%]a#|%]a(X%]a(h%]a!Y%]a!Z%]a~Oj%]a|%]a!P%]a(o%]a~P&BuOj<gO|)zO!P){O(p%PO~P&@nOj<gO|)zO!P){O(o$}O~P&BuO|0ZO}0ZO!P0[OPyaZyajyanya!hya!iya!kya!oya#jya#kya#lya#mya#nya#oya#pya#qya#rya#tya#vya#xya#yya#|ya(Xya(hya(oya(pya!Yya!Zya~O|)zO!P){OP$naZ$naj$nan$na}$na!h$na!i$na!k$na!o$na#j$na#k$na#l$na#m$na#n$na#o$na#p$na#q$na#r$na#t$na#v$na#x$na#y$na#|$na(X$na(h$na(o$na(p$na!Y$na!Z$na~O|)zO!P){OP$paZ$paj$pan$pa}$pa!h$pa!i$pa!k$pa!o$pa#j$pa#k$pa#l$pa#m$pa#n$pa#o$pa#p$pa#q$pa#r$pa#t$pa#v$pa#x$pa#y$pa#|$pa(X$pa(h$pa(o$pa(p$pa!Y$pa!Z$pa~OP%OaZ%Oan%Oa}%Oa!h%Oa!i%Oa!k%Oa!o%Oa#j%Oa#k%Oa#l%Oa#m%Oa#n%Oa#o%Oa#p%Oa#q%Oa#r%Oa#t%Oa#v%Oa#x%Oa#y%Oa#|%Oa(X%Oa(h%Oa!Y%Oa!Z%Oa~P&'UO#|$jq!Y$jq!Z$jq~P#C|O#|$kq!Y$kq!Z$kq~P#C|O!Z8vO~O#|8wO~P!0}O!d#uO!Y'^i!j'^i~O!d#uO(h'kO!Y'^i!j'^i~O!Y/cO!j(uq~O!V'`i!Y'`i~P#-]O!Y/kO!V(vq~O!V8}O~P#-]O!V8}O~Of(Vy!Y(Vy~P!0}O!Y'ga!['ga~P#-]O`%Vq![%Vq'r%Vq!Y%Vq~P#-]OZ9SO~O!Y0rO!Z)Oq~O#[9WO!Y'ia!Z'ia~O!Y5UO!Z({i~P#C|OP[XZ[Xn[X|[X}[X!P[X!V[X!Y[X!h[X!i[X!k[X!o[X#[[X#geX#j[X#k[X#l[X#m[X#n[X#o[X#p[X#q[X#r[X#t[X#v[X#x[X#y[X$O[X(X[X(h[X(o[X(p[X~O!d%TX#r%TX~P'#`O![1[O%c9[O~O'}TO(QUO([9aO~O!Y1gO!Z(|q~O!j9dO~O!j9eO~O!j9fO~O!j9fO~P%[O#[9iO!Y#dy!Z#dy~O!Y#dy!Z#dy~P#C|O!['ZO%c9nO~O#|#zy!Y#zy!Z#zy~P#C|OP$wiZ$win$wi}$wi!h$wi!i$wi!k$wi!o$wi#j$wi#k$wi#l$wi#m$wi#n$wi#o$wi#p$wi#q$wi#r$wi#t$wi#v$wi#x$wi#y$wi#|$wi(X$wi(h$wi!Y$wi!Z$wi~P&'UO|)zO!P){O(p%POP'baZ'baj'ban'ba}'ba!h'ba!i'ba!k'ba!o'ba#j'ba#k'ba#l'ba#m'ba#n'ba#o'ba#p'ba#q'ba#r'ba#t'ba#v'ba#x'ba#y'ba#|'ba(X'ba(h'ba(o'ba!Y'ba!Z'ba~O|)zO!P){OP'daZ'daj'dan'da}'da!h'da!i'da!k'da!o'da#j'da#k'da#l'da#m'da#n'da#o'da#p'da#q'da#r'da#t'da#v'da#x'da#y'da#|'da(X'da(h'da(o'da(p'da!Y'da!Z'da~O(o$}OP%ZiZ%Zij%Zin%Zi|%Zi}%Zi!P%Zi!h%Zi!i%Zi!k%Zi!o%Zi#j%Zi#k%Zi#l%Zi#m%Zi#n%Zi#o%Zi#p%Zi#q%Zi#r%Zi#t%Zi#v%Zi#x%Zi#y%Zi#|%Zi(X%Zi(h%Zi(p%Zi!Y%Zi!Z%Zi~O(p%POP%]iZ%]ij%]in%]i|%]i}%]i!P%]i!h%]i!i%]i!k%]i!o%]i#j%]i#k%]i#l%]i#m%]i#n%]i#o%]i#p%]i#q%]i#r%]i#t%]i#v%]i#x%]i#y%]i#|%]i(X%]i(h%]i(o%]i!Y%]i!Z%]i~O#|$ky!Y$ky!Z$ky~P#C|O#|#_y!Y#_y!Z#_y~P#C|O!d#uO!Y'^q!j'^q~O!Y/cO!j(uy~O!V'`q!Y'`q~P#-]O!V9wO~P#-]O!Y0rO!Z)Oy~O!Y5UO!Z({q~O![1[O%c:OO~O!j:RO~O!['ZO%c:WO~OP$wqZ$wqn$wq}$wq!h$wq!i$wq!k$wq!o$wq#j$wq#k$wq#l$wq#m$wq#n$wq#o$wq#p$wq#q$wq#r$wq#t$wq#v$wq#x$wq#y$wq#|$wq(X$wq(h$wq!Y$wq!Z$wq~P&'UO|)zO!P){O(p%POP'caZ'caj'can'ca}'ca!h'ca!i'ca!k'ca!o'ca#j'ca#k'ca#l'ca#m'ca#n'ca#o'ca#p'ca#q'ca#r'ca#t'ca#v'ca#x'ca#y'ca#|'ca(X'ca(h'ca(o'ca!Y'ca!Z'ca~O|)zO!P){OP'eaZ'eaj'ean'ea}'ea!h'ea!i'ea!k'ea!o'ea#j'ea#k'ea#l'ea#m'ea#n'ea#o'ea#p'ea#q'ea#r'ea#t'ea#v'ea#x'ea#y'ea#|'ea(X'ea(h'ea(o'ea(p'ea!Y'ea!Z'ea~OP$yqZ$yqn$yq}$yq!h$yq!i$yq!k$yq!o$yq#j$yq#k$yq#l$yq#m$yq#n$yq#o$yq#p$yq#q$yq#r$yq#t$yq#v$yq#x$yq#y$yq#|$yq(X$yq(h$yq!Y$yq!Z$yq~P&'UOf%_!Z!Y%_!Z#[%_!Z#|%_!Z~P!0}O!Y'iq!Z'iq~P#C|O!Y#d!Z!Z#d!Z~P#C|O#g%_!ZP%_!ZZ%_!Z`%_!Zn%_!Z}%_!Z!Y%_!Z!h%_!Z!i%_!Z!k%_!Z!o%_!Z#j%_!Z#k%_!Z#l%_!Z#m%_!Z#n%_!Z#o%_!Z#p%_!Z#q%_!Z#r%_!Z#t%_!Z#v%_!Z#x%_!Z#y%_!Z'r%_!Z(X%_!Z(h%_!Z!j%_!Z!V%_!Z'p%_!Z#[%_!Zr%_!Z![%_!Z%c%_!Z!d%_!Z~P#-]OP%_!ZZ%_!Zn%_!Z}%_!Z!h%_!Z!i%_!Z!k%_!Z!o%_!Z#j%_!Z#k%_!Z#l%_!Z#m%_!Z#n%_!Z#o%_!Z#p%_!Z#q%_!Z#r%_!Z#t%_!Z#v%_!Z#x%_!Z#y%_!Z#|%_!Z(X%_!Z(h%_!Z!Y%_!Z!Z%_!Z~P&'UOr(]X~P1qO'|!lO~P!*fO!VeX!YeX#[eX~P'#`OP[XZ[Xn[X|[X}[X!P[X!Y[X!YeX!h[X!i[X!k[X!o[X#[[X#[eX#geX#j[X#k[X#l[X#m[X#n[X#o[X#p[X#q[X#r[X#t[X#v[X#x[X#y[X$O[X(X[X(h[X(o[X(p[X~O!deX!j[X!jeX(heX~P'ASOP:cOQ:cORfOc<[Od!iOlkOn:cOokOpkOvkOx:cOz:cO!PWO!TkO!UkO![XO!f:fO!kZO!n:cO!o:cO!p:cO!r:gO!t:jO!w!hO$T!kO'{)YO'}TO(QUO(XVO(g[O(t<YO~O!Y:wO!Z$ma~Og%VOl%WOn$tOo$sOp$sOv%XOx%YOz;RO!P${O![$|O!f<aO!k$xO#f;XO$T%^O$o;TO$q;VO$t%_O'{(pO'}TO(QUO(X$uO(o$}O(p%PO~O#s)aO~P'ExO!Z[X!ZeX~P'ASO#g:kO~O!d#uO#g:kO~O#[:{O~O#r:pO~O#[;ZO!Y(mX!Z(mX~O#[:{O!Y(kX!Z(kX~O#g;[O~Of;^O~P!0}O#g;cO~O#g;dO~O!d#uO#g;eO~O!d#uO#g;[O~O#|;fO~P#C|O#g;gO~O#g;hO~O#g;mO~O#g;nO~O#g;oO~O#g;pO~O#|;qO~P!0}O#|;rO~P!0}O!i#P#Q#S#T#W#e#f#q(t$o$q$t%W%b%c%d%k%m%p%q%s%u~'vS#k!U't'|#lo#j#mn|'u$Y'u'{$[([~",goto:"$2p)SPPPPP)TPP)WP)iP*x.|PPPP5pPP6WPP<S?gP?zP?zPPP?zPAxP?zP?zP?zPA|PPBRPBlPGdPPPGhPPPPGhJiPPPJoKjPGhPMxPPPP!!WGhPPPGhPGhP!$fGhP!'z!(|!)VP!)y!)}!)yPPPPP!-Y!(|PP!-v!.pP!1dGhGh!1i!4s!9Y!9Y!=OPPP!=VGhPPPPPPPPPPP!@dP!AqPPGh!CSPGhPGhGhGhGhPGh!DfP!GnP!JrP!Jv!KQ!KU!KUP!GkP!KY!KYP!N^P!NbGhGh!Nh##k?zP?zP?z?zP#$v?z?z#'O?z#)k?z#+m?z?z#,[#.f#.f#.j#.r#.f#.zP#.fP?z#/d?z#3R?z?z5pPPP#6vPPP#7a#7aP#7aP#7w#7aPP#7}P#7tP#7t#8b#7t#8|#9S5m)W#9V)WP#9^#9^#9^P)WP)WP)WP)WPP)WP#9d#9gP#9g)WP#9kP#9nP)WP)WP)WP)WP)WP)W)WPP#9t#9z#:V#:]#:c#:i#:o#:}#;T#;Z#;e#;k#;u#<U#<[#<|#=`#=f#=l#=z#>a#@O#@^#@d#Ax#BW#Cr#DQ#DW#D^#Dd#Dn#Dt#Dz#EU#Eh#EnPPPPPPPPPP#EtPPPPPPP#Fi#Ip#KP#KW#K`PPPP$!d$%Z$+r$+u$+x$,q$,t$,w$-O$-WPP$-^$-b$.Y$/X$/]$/qPP$/u$/{$0PP$0S$0W$0Z$1P$1h$2P$2T$2W$2Z$2a$2d$2h$2lR!{RoqOXst!Z#c%j&m&o&p&r,h,m1w1zY!uQ'Z-Y1[5]Q%pvQ%xyQ&P|Q&e!VS'R!e-QQ'a!iS'g!r!xS*c$|*hQ+f%yQ+s&RQ,X&_Q-W'YQ-b'bQ-j'hQ/|*jQ1f,YR;Y:g%OdOPWXYZstuvw!Z!`!g!o#R#V#Y#c#n#t#x#{$O$P$Q$R$S$T$U$V$W$X$Y$a$e%j%p%}&f&i&m&o&p&r&v'O']'m'}(P(V(^(r(v(z)y+O+S,e,h,m-^-f-t-z.l.s0[0a0q1_1o1p1r1t1w1z1|2m2s3Z5Y5d5t5u5x6]7w7|8]8gS#p]:d!r)[$[$m'S)n,y,|.{2]3p5W6S9W9i:c:f:g:j:k:l:m:n:o:p:q:r:s:t:u:v:w:{;Y;Z;[;^;e;f;o;p<]Q*u%ZQ+k%{Q,Z&bQ,b&jQ.c;QQ0h+^Q0l+`Q0w+lQ1n,`Q2{.[Q4v0rQ5k1gQ6i3PQ6u;RQ7h4wR8m6j&|kOPWXYZstuvw!Z!`!g!o#R#V#Y#c#n#t#x#{$O$P$Q$R$S$T$U$V$W$X$Y$[$a$e$m%j%p%}&f&i&j&m&o&p&r&v'O'S']'m'}(P(V(^(r(v(z)n)y+O+S+^,e,h,m,y,|-^-f-t-z.[.l.s.{0[0a0q1_1o1p1r1t1w1z1|2]2m2s3P3Z3p5W5Y5d5t5u5x6S6]6j7w7|8]8g9W9i:c:f:g:j:k:l:m:n:o:p:q:r:s:t:u:v:w:{;Y;Z;[;^;e;f;o;p<]t!nQ!r!u!x!y'R'Y'Z'g'h'i-Q-W-Y-j1[5]5_$v$si#u#w$c$d$x${%O%Q%[%]%a)u){)}*P*R*Y*`*p*q+]+`+w+z.Z.i/Z/j/k/m0Q0S0^1R1U1^3O3x4S4[4f4n4p5c6g7T7^7y8j8w9[9n:O:W:y:z:|:};O;P;S;T;U;V;W;X;_;`;a;b;c;d;g;h;i;j;k;l;m;n;q;r<Y<b<c<f<gQ&S|Q'P!eS'V%f-TQ+k%{Q,Z&bQ0]*yQ0w+lQ0|+rQ1m,_Q1n,`Q4v0rQ5P1OQ5k1gQ5n1iQ5o1lQ7h4wQ7k4|Q8U5qQ9V7lR9b8RrnOXst!V!Z#c%j&d&m&o&p&r,h,m1w1zR,]&f&v^OPXYstuvwz!Z!`!g!j!o#R#c#n#t#x#{$O$P$Q$R$S$T$U$V$W$X$Y$[$a$e$m%j%p%}&f&i&j&m&o&p&r&v'O']'m(P(V(^(r(v(z)n)y+O+S+^,e,h,m,y,|-^-f-t-z.[.l.s.{0[0a0q1_1o1p1r1t1w1z1|2]2m2s3P3Z3p5W5Y5d5t5u5x6S6]6j7w7|8]8g9W9i:c:f:g:j:k:l:m:n:o:p:q:r:s:t:u:v:w:{;Y;Z;[;^;e;f;o;p<[<][#[WZ#V#Y'S'}!S%gm#g#h#k%b%e(W(b(c(d+Q+R+T,d,z-x.O.P.Q.S2P2w2x6R6dQ%sxQ%wyS%||&RQ&Y!TQ'^!hQ'`!iQ(k#rS*V$x*ZS+e%x%yQ+i%{Q,S&]Q,W&_S-a'a'bQ.^(lQ/g*WQ0p+fQ0v+lQ0x+mQ0{+qQ1a,TS1e,X,YQ2i-bQ3y/cQ4u0rQ4y0uQ5O0}Q5j1fQ7Q3zQ7g4wQ7j4{Q9R7fR9y9S!O$zi#w%O%Q%[%]%a)}*P*Y*p*q.i/j0Q0S0^3x4f8w<Y<b<c!S%uy!i!t%w%x%y'Q'`'a'b'f'p*b+e+f,}-a-b-i/t0p2b2i2p4^Q+_%sQ+x&VQ+{&WQ,V&_Q.](kQ1`,SU1d,W,X,YQ3Q.^Q5e1aS5i1e1fQ8Q5j#W<^#u$c$d$x${)u){*R*`+]+`+w+z.Z/Z/k/m1R1U1^3O4S4[4n4p5c6g7T7^7y8j9[9n:O:W:|;O;S;U;W;_;a;c;g;i;k;m;q<f<go<_:y:z:};P;T;V;X;`;b;d;h;j;l;n;rW%Ti%V*r<YS&V!Q&dQ&W!RQ&X!SR+v&T$w%Si#u#w$c$d$x${%O%Q%[%]%a)u){)}*P*R*Y*`*p*q+]+`+w+z.Z.i/Z/j/k/m0Q0S0^1R1U1^3O3x4S4[4f4n4p5c6g7T7^7y8j8w9[9n:O:W:y:z:|:};O;P;S;T;U;V;W;X;_;`;a;b;c;d;g;h;i;j;k;l;m;n;q;r<Y<b<c<f<gT)v$u)wV*v%Z;Q;RU'V!e%f-TS(y#y#zQ+p&OS.V(g(hQ1V+|Q4g0ZR7p5U&|kOPWXYZstuvw!Z!`!g!o#R#V#Y#c#n#t#x#{$O$P$Q$R$S$T$U$V$W$X$Y$[$a$e$m%j%p%}&f&i&j&m&o&p&r&v'O'S']'m'}(P(V(^(r(v(z)n)y+O+S+^,e,h,m,y,|-^-f-t-z.[.l.s.{0[0a0q1_1o1p1r1t1w1z1|2]2m2s3P3Z3p5W5Y5d5t5u5x6S6]6j7w7|8]8g9W9i:c:f:g:j:k:l:m:n:o:p:q:r:s:t:u:v:w:{;Y;Z;[;^;e;f;o;p<]$i$`c#X#d%n%o%q'|(S(n(u(})O)P)Q)R)S)T)U)V)W)X)Z)^)b)l+Z+o-O-m-r-w-y.h.n.r.t.u.v/V0_2W2Z2k2r3Y3_3`3a3b3c3d3e3f3g3h3i3j3k3n3o3t4k4s6U6[6a6o6p6y6z7r8a8e8n8t8u9k9{:S:e<PT#SV#T&}kOPWXYZstuvw!Z!`!g!o#R#V#Y#c#n#t#x#{$O$P$Q$R$S$T$U$V$W$X$Y$[$a$e$m%j%p%}&f&i&j&m&o&p&r&v'O'S']'m'}(P(V(^(r(v(z)n)y+O+S+^,e,h,m,y,|-^-f-t-z.[.l.s.{0[0a0q1_1o1p1r1t1w1z1|2]2m2s3P3Z3p5W5Y5d5t5u5x6S6]6j7w7|8]8g9W9i:c:f:g:j:k:l:m:n:o:p:q:r:s:t:u:v:w:{;Y;Z;[;^;e;f;o;p<]Q'T!eR2^-Qv!nQ!e!r!u!x!y'R'Y'Z'g'h'i-Q-W-Y-j1[5]5_S*b$|*hS/t*c*jQ/}*kQ1X,OQ4^/|R4a0PnqOXst!Z#c%j&m&o&p&r,h,m1w1zQ&t!^Q'q!wS(m#t:kQ+c%vQ,Q&YQ,R&[Q-_'_Q-l'jS.g(r;[S0`+O;eQ0n+dQ1Z,PQ2O,oQ2Q,pQ2Y,{Q2g-`Q2j-dS4l0a;oQ4q0oS4t0q;pQ6T2[Q6X2hQ6^2oQ7e4rQ8b6VQ8c6YQ8f6_R9h8_$d$_c#X#d%o%q'|(S(n(u(})O)P)Q)R)S)T)U)V)W)X)Z)^)b)l+Z+o-O-m-r-w-y.h.n.r.u.v/V0_2W2Z2k2r3Y3_3`3a3b3c3d3e3f3g3h3i3j3k3n3o3t4k4s6U6[6a6o6p6y6z7r8a8e8n8t8u9k9{:S:e<PS(j#o'dU*o%R(q3mS+Y%n.tQ2|0hQ6f2{Q8l6iR9o8m$d$^c#X#d%o%q'|(S(n(u(})O)P)Q)R)S)T)U)V)W)X)Z)^)b)l+Z+o-O-m-r-w-y.h.n.r.u.v/V0_2W2Z2k2r3Y3_3`3a3b3c3d3e3f3g3h3i3j3k3n3o3t4k4s6U6[6a6o6p6y6z7r8a8e8n8t8u9k9{:S:e<PS(i#o'dS({#z$_S+X%n.tS.W(h(jQ.w)]Q0e+YR2y.X&|kOPWXYZstuvw!Z!`!g!o#R#V#Y#c#n#t#x#{$O$P$Q$R$S$T$U$V$W$X$Y$[$a$e$m%j%p%}&f&i&j&m&o&p&r&v'O'S']'m'}(P(V(^(r(v(z)n)y+O+S+^,e,h,m,y,|-^-f-t-z.[.l.s.{0[0a0q1_1o1p1r1t1w1z1|2]2m2s3P3Z3p5W5Y5d5t5u5x6S6]6j7w7|8]8g9W9i:c:f:g:j:k:l:m:n:o:p:q:r:s:t:u:v:w:{;Y;Z;[;^;e;f;o;p<]S#p]:dQ&o!XQ&p!YQ&r![Q&s!]R1v,kQ'[!hQ+[%sQ-]'^S.Y(k+_Q2e-[W2}.].^0g0iQ6W2fU6e2z2|3QS8i6f6hS9m8k8lS:U9l9oQ:^:VR:a:_U!vQ'Z-YT5Z1[5]!Q_OXZ`st!V!Z#c#g%b%j&d&f&m&o&p&r(d,h,m.P1w1z]!pQ!r'Z-Y1[5]T#p]:d%Y{OPWXYZstuvw!Z!`!g!o#R#V#Y#c#n#t#x#{$O$P$Q$R$S$T$U$V$W$X$Y$a$e%j%p%}&f&i&j&m&o&p&r&v'O']'m'}(P(V(^(r(v(z)y+O+S+^,e,h,m-^-f-t-z.[.l.s0[0a0q1_1o1p1r1t1w1z1|2m2s3P3Z5Y5d5t5u5x6]6j7w7|8]8gS(y#y#zS.V(g(h!s;v$[$m'S)n,y,|.{2]3p5W6S9W9i:c:f:g:j:k:l:m:n:o:p:q:r:s:t:u:v:w:{;Y;Z;[;^;e;f;o;p<]Y!tQ'Z-Y1[5]Q'f!rS'p!u!xS'r!y5_S-i'g'hQ-k'iR2p-jQ'o!tS(`#f1qS-h'f'rQ/f*VQ/r*bQ2q-kQ4O/gS4X/s/}Q7P3yS7[4_4aQ8y7QR9Q7_Q#vbQ'n!tS(_#f1qS(a#l*}Q+P%cQ+a%tQ+g%zU-g'f'o'rQ-{(`Q/e*VQ/q*bQ/w*eQ0m+bQ1b,US2n-h-kQ2v.TS3}/f/gS4W/r/}Q4Z/vQ4]/xQ5g1cQ6`2qQ7O3yQ7S4OS7W4X4aQ7]4`Q8O5hS8x7P7QQ8|7XQ9O7[Q9_8PQ9u8yQ9v8}Q9x9QQ:Q9`Q:Y9wQ;y;tQ<U;}R<V<OV!vQ'Z-Y%YaOPWXYZstuvw!Z!`!g!o#R#V#Y#c#n#t#x#{$O$P$Q$R$S$T$U$V$W$X$Y$a$e%j%p%}&f&i&j&m&o&p&r&v'O']'m'}(P(V(^(r(v(z)y+O+S+^,e,h,m-^-f-t-z.[.l.s0[0a0q1_1o1p1r1t1w1z1|2m2s3P3Z5Y5d5t5u5x6]6j7w7|8]8gS#vz!j!r;s$[$m'S)n,y,|.{2]3p5W6S9W9i:c:f:g:j:k:l:m:n:o:p:q:r:s:t:u:v:w:{;Y;Z;[;^;e;f;o;p<]R;y<[%YbOPWXYZstuvw!Z!`!g!o#R#V#Y#c#n#t#x#{$O$P$Q$R$S$T$U$V$W$X$Y$a$e%j%p%}&f&i&j&m&o&p&r&v'O']'m'}(P(V(^(r(v(z)y+O+S+^,e,h,m-^-f-t-z.[.l.s0[0a0q1_1o1p1r1t1w1z1|2m2s3P3Z5Y5d5t5u5x6]6j7w7|8]8gQ%cj!S%ty!i!t%w%x%y'Q'`'a'b'f'p*b+e+f,}-a-b-i/t0p2b2i2p4^S%zz!jQ+b%uQ,U&_W1c,V,W,X,YU5h1d1e1fS8P5i5jQ9`8Q!r;t$[$m'S)n,y,|.{2]3p5W6S9W9i:c:f:g:j:k:l:m:n:o:p:q:r:s:t:u:v:w:{;Y;Z;[;^;e;f;o;p<]Q;}<ZR<O<[$|eOPXYstuvw!Z!`!g!o#R#c#n#t#x#{$O$P$Q$R$S$T$U$V$W$X$Y$a$e%j%p%}&f&i&m&o&p&r&v'O']'m(P(V(^(r(v(z)y+O+S+^,e,h,m-^-f-t-z.[.l.s0[0a0q1_1o1p1r1t1w1z1|2m2s3P3Z5Y5d5t5u5x6]6j7w7|8]8gY#aWZ#V#Y'}!S%gm#g#h#k%b%e(W(b(c(d+Q+R+T,d,z-x.O.P.Q.S2P2w2x6R6dQ,c&j!p;u$[$m)n,y,|.{2]3p5W6S9W9i:c:f:g:j:k:l:m:n:o:p:q:r:s:t:u:v:w:{;Y;Z;[;^;e;f;o;p<]R;x'SS'W!e%fR2`-T%OdOPWXYZstuvw!Z!`!g!o#R#V#Y#c#n#t#x#{$O$P$Q$R$S$T$U$V$W$X$Y$a$e%j%p%}&f&i&m&o&p&r&v'O']'m'}(P(V(^(r(v(z)y+O+S,e,h,m-^-f-t-z.l.s0[0a0q1_1o1p1r1t1w1z1|2m2s3Z5Y5d5t5u5x6]7w7|8]8g!r)[$[$m'S)n,y,|.{2]3p5W6S9W9i:c:f:g:j:k:l:m:n:o:p:q:r:s:t:u:v:w:{;Y;Z;[;^;e;f;o;p<]Q,b&jQ0h+^Q2{.[Q6i3PR8m6j!b$Uc#X%n'|(S(n(u)W)X)^)b+o-m-r-w-y.h.n/V0_2k2r3Y3k4k4s6[6a6o8e9k:e!P:r)Z)l-O.t2W2Z3_3i3j3n3t6U6p6y6z7r8a8n8t8u9{:S<P!f$Wc#X%n'|(S(n(u)T)U)W)X)^)b+o-m-r-w-y.h.n/V0_2k2r3Y3k4k4s6[6a6o8e9k:e!T:t)Z)l-O.t2W2Z3_3f3g3i3j3n3t6U6p6y6z7r8a8n8t8u9{:S<P!^$[c#X%n'|(S(n(u)^)b+o-m-r-w-y.h.n/V0_2k2r3Y3k4k4s6[6a6o8e9k:eQ3x/az<])Z)l-O.t2W2Z3_3n3t6U6p6y6z7r8a8n8t8u9{:S<PQ<b<dR<c<e&|kOPWXYZstuvw!Z!`!g!o#R#V#Y#c#n#t#x#{$O$P$Q$R$S$T$U$V$W$X$Y$[$a$e$m%j%p%}&f&i&j&m&o&p&r&v'O'S']'m'}(P(V(^(r(v(z)n)y+O+S+^,e,h,m,y,|-^-f-t-z.[.l.s.{0[0a0q1_1o1p1r1t1w1z1|2]2m2s3P3Z3p5W5Y5d5t5u5x6S6]6j7w7|8]8g9W9i:c:f:g:j:k:l:m:n:o:p:q:r:s:t:u:v:w:{;Y;Z;[;^;e;f;o;p<]S$nh$oR3q.z'TgOPWXYZhstuvw!Z!`!g!o#R#V#Y#c#n#t#x#{$O$P$Q$R$S$T$U$V$W$X$Y$[$a$e$m$o%j%p%}&f&i&j&m&o&p&r&v'O'S']'m'}(P(V(^(r(v(z)n)y+O+S+^,e,h,m,y,|-^-f-t-z.[.l.s.z.{0[0a0q1_1o1p1r1t1w1z1|2]2m2s3P3Z3p5W5Y5d5t5u5x6S6]6j7w7|8]8g9W9i:c:f:g:j:k:l:m:n:o:p:q:r:s:t:u:v:w:{;Y;Z;[;^;e;f;o;p<]T$jf$pQ$hfS)e$k)iR)q$pT$if$pT)g$k)i'ThOPWXYZhstuvw!Z!`!g!o#R#V#Y#c#n#t#x#{$O$P$Q$R$S$T$U$V$W$X$Y$[$a$e$m$o%j%p%}&f&i&j&m&o&p&r&v'O'S']'m'}(P(V(^(r(v(z)n)y+O+S+^,e,h,m,y,|-^-f-t-z.[.l.s.z.{0[0a0q1_1o1p1r1t1w1z1|2]2m2s3P3Z3p5W5Y5d5t5u5x6S6]6j7w7|8]8g9W9i:c:f:g:j:k:l:m:n:o:p:q:r:s:t:u:v:w:{;Y;Z;[;^;e;f;o;p<]T$nh$oQ$qhR)p$o%YjOPWXYZstuvw!Z!`!g!o#R#V#Y#c#n#t#x#{$O$P$Q$R$S$T$U$V$W$X$Y$a$e%j%p%}&f&i&j&m&o&p&r&v'O']'m'}(P(V(^(r(v(z)y+O+S+^,e,h,m-^-f-t-z.[.l.s0[0a0q1_1o1p1r1t1w1z1|2m2s3P3Z5Y5d5t5u5x6]6j7w7|8]8g!s<Z$[$m'S)n,y,|.{2]3p5W6S9W9i:c:f:g:j:k:l:m:n:o:p:q:r:s:t:u:v:w:{;Y;Z;[;^;e;f;o;p<]#clOPXZst!Z!`!o#R#c#n#{$m%j&f&i&j&m&o&p&r&v'O'](z)n+S+^,e,h,m-^.[.{0[1_1o1p1r1t1w1z1|3P3p5Y5d5t5u5x6j7w7|8]!O%Ri#w%O%Q%[%]%a)}*P*Y*p*q.i/j0Q0S0^3x4f8w<Y<b<c#W(q#u$c$d$x${)u){*R*`+]+`+w+z.Z/Z/k/m1R1U1^3O4S4[4n4p5c6g7T7^7y8j9[9n:O:W:|;O;S;U;W;_;a;c;g;i;k;m;q<f<gQ*z%_Q/W)zo3m:y:z:};P;T;V;X;`;b;d;h;j;l;n;r!O$yi#w%O%Q%[%]%a)}*P*Y*p*q.i/j0Q0S0^3x4f8w<Y<b<cQ*[$zS*e$|*hQ*{%`Q/x*f#W;{#u$c$d$x${)u){*R*`+]+`+w+z.Z/Z/k/m1R1U1^3O4S4[4n4p5c6g7T7^7y8j9[9n:O:W:|;O;S;U;W;_;a;c;g;i;k;m;q<f<gn;|:y:z:};P;T;V;X;`;b;d;h;j;l;n;rQ<Q<^Q<R<_Q<S<`R<T<a!O%Ri#w%O%Q%[%]%a)}*P*Y*p*q.i/j0Q0S0^3x4f8w<Y<b<c#W(q#u$c$d$x${)u){*R*`+]+`+w+z.Z/Z/k/m1R1U1^3O4S4[4n4p5c6g7T7^7y8j9[9n:O:W:|;O;S;U;W;_;a;c;g;i;k;m;q<f<go3m:y:z:};P;T;V;X;`;b;d;h;j;l;n;rnoOXst!Z#c%j&m&o&p&r,h,m1w1zQ*_${Q,v&yQ,w&{R4R/k$v%Si#u#w$c$d$x${%O%Q%[%]%a)u){)}*P*R*Y*`*p*q+]+`+w+z.Z.i/Z/j/k/m0Q0S0^1R1U1^3O3x4S4[4f4n4p5c6g7T7^7y8j8w9[9n:O:W:y:z:|:};O;P;S;T;U;V;W;X;_;`;a;b;c;d;g;h;i;j;k;l;m;n;q;r<Y<b<c<f<gQ+y&WQ1T+{Q5S1SR7o5TT*g$|*hS*g$|*hT5[1[5]S/v*d5YT4`0O7wQ+a%tQ/w*eQ0m+bQ1b,UQ5g1cQ8O5hQ9_8PR:Q9`!O%Oi#w%O%Q%[%]%a)}*P*Y*p*q.i/j0Q0S0^3x4f8w<Y<b<cr)}$v(s*O*n*|/i0U0V3W4P4j6}7`9t;z<W<XS0Q*m0R#W:|#u$c$d$x${)u){*R*`+]+`+w+z.Z/Z/k/m1R1U1^3O4S4[4n4p5c6g7T7^7y8j9[9n:O:W:|;O;S;U;W;_;a;c;g;i;k;m;q<f<gn:}:y:z:};P;T;V;X;`;b;d;h;j;l;n;r!^;_(o)`*U*^._.b.f/S/X/a/n0f1Q1S3T4Q4U5R5T6k6n7U7Y7b7d8{9P:X<d<e`;`3l6q6t6x8o9p9s:bS;i.a3UT;j6s8r!O%Qi#w%O%Q%[%]%a)}*P*Y*p*q.i/j0Q0S0^3x4f8w<Y<b<cv*P$v(s*Q*m*|/]/i0U0V3W4P4b4j6}7`9t;z<W<XS0S*n0T#W;O#u$c$d$x${)u){*R*`+]+`+w+z.Z/Z/k/m1R1U1^3O4S4[4n4p5c6g7T7^7y8j9[9n:O:W:|;O;S;U;W;_;a;c;g;i;k;m;q<f<gn;P:y:z:};P;T;V;X;`;b;d;h;j;l;n;r!b;a(o)`*U*^.`.a.f/S/X/a/n0f1Q1S3R3T4Q4U5R5T6k6l6n7U7Y7b7d8{9P:X<d<ed;b3l6r6s6x8o8p9p9q9s:bS;k.b3VT;l6t8srnOXst!V!Z#c%j&d&m&o&p&r,h,m1w1zQ&a!UR,e&jrnOXst!V!Z#c%j&d&m&o&p&r,h,m1w1zR&a!UQ+}&XR1P+vsnOXst!V!Z#c%j&d&m&o&p&r,h,m1w1zQ1],SS5b1`1aU7x5`5a5eS9Z7z7{S9|9Y9]Q:Z9}R:`:[Q&h!VR,^&dR5n1iS%||&RR0x+mQ&m!WR,h&nR,n&sT1x,m1zR,r&tQ,q&tR2R,rQ't!zR-n'tSsOtQ#cXT%ms#cQ!}TR'v!}Q#QUR'x#QQ)w$uR/T)wQ#TVR'z#TQ#WWU(Q#W(R-uQ(R#XR-u(SQ-R'TR2_-RQ.j(sR3X.jQ.m(uS3[.m3]R3].nQ-Y'ZR2c-YY!rQ'Z-Y1[5]R'e!rS#^W%eU(X#^(Y-vQ(Y#_R-v(TQ-U'WR2a-Ut`OXst!V!Z#c%j&d&f&m&o&p&r,h,m1w1zS#gZ%bU#q`#g.PR.P(dQ(e#iQ-|(aW.U(e-|2t6bQ2t-}R6b2uQ)i$kR.|)iQ$ohR)o$oQ$bcU)_$b-q:xQ-q:eR:x)lQ/d*VW3{/d3|7R8zU3|/e/f/gS7R3}4OR8z7S$X)|$v(o(s)`*U*^*m*n*w*x*|.a.b.d.e.f/S/X/]/_/a/i/n0U0V0f1Q1S3R3S3T3W3l4P4Q4U4b4d4j5R5T6k6l6m6n6s6t6v6w6x6}7U7Y7`7b7d8o8p8q8{9P9p9q9r9s9t:X:b;z<W<X<d<eQ/l*^U4T/l4V7VQ4V/nR7V4UQ*h$|R/z*hr*O$v(s*m*n*|/i0U0V3W4P4j6}7`9t;z<W<X!^._(o)`*U*^.a.b.f/S/X/a/n0f1Q1S3T4Q4U5R5T6k6n7U7Y7b7d8{9P:X<d<eU/^*O._6qa6q3l6s6t6x8o9p9s:bQ0R*mQ3U.aU4c0R3U8rR8r6sv*Q$v(s*m*n*|/]/i0U0V3W4P4b4j6}7`9t;z<W<X!b.`(o)`*U*^.a.b.f/S/X/a/n0f1Q1S3R3T4Q4U5R5T6k6l6n7U7Y7b7d8{9P:X<d<eU/`*Q.`6re6r3l6s6t6x8o8p9p9q9s:bQ0T*nQ3V.bU4e0T3V8sR8s6tQ*s%UR0X*sQ4o0fR7c4oQ+U%hR0d+UQ5V1VS7q5V9XR9X7rQ,P&YR1Y,PQ5]1[R7u5]Q1h,ZS5l1h8SR8S5nQ0s+iW4x0s4z7i9TQ4z0vQ7i4yR9T7jQ+n%|R0y+nQ1z,mR5|1zYrOXst#cQ&q!ZQ+W%jQ,g&mQ,i&oQ,j&pQ,l&rQ1u,hS1x,m1zR5{1wQ%lpQ&u!_Q&x!aQ&z!bQ&|!cQ'l!tQ+V%iQ+c%vQ+u&SQ,]&hQ,t&wW-e'f'n'o'rQ-l'jQ/y*gQ0n+dS1k,^,aQ2S,sQ2T,vQ2U,wQ2j-dW2l-g-h-k-mQ4q0oQ4}0|Q5Q1QQ5f1bQ5p1mQ5z1vU6Z2k2n2qQ6^2oQ7e4rQ7m5PQ7n5RQ7t5[Q7}5gQ8T5oS8d6[6`Q8f6_Q9U7kQ9^8OQ9c8UQ9j8eQ9z9VQ:P9_Q:T9kR:]:QQ%vyQ'_!iQ'j!tU+d%w%x%yQ,{'QU-`'`'a'bS-d'f'pQ/p*bS0o+e+fQ2[,}S2h-a-bQ2o-iQ4Y/tQ4r0pQ6V2bQ6Y2iQ6_2pR7Z4^S$wi<YR*t%VU%Ui%V<YR0W*rQ$viS(o#u+`Q(s#wS)`$c$dQ*U$xQ*^${Q*m%OQ*n%QQ*w%[Q*x%]Q*|%aQ.a:|Q.b;OQ.d;SQ.e;UQ.f;WQ/S)uS/X){/ZQ/])}Q/_*PQ/a*RQ/i*YQ/n*`Q0U*pQ0V*qh0f+].Z1^3O5c6g7y8j9[9n:O:WQ1Q+wQ1S+zQ3R;_Q3S;aQ3T;cQ3W.iS3l:y:zQ4P/jQ4Q/kQ4U/mQ4b0QQ4d0SQ4j0^Q5R1RQ5T1UQ6k;gQ6l;iQ6m;kQ6n;mQ6s:}Q6t;PQ6v;TQ6w;VQ6x;XQ6}3xQ7U4SQ7Y4[Q7`4fQ7b4nQ7d4pQ8o;dQ8p;`Q8q;bQ8{7TQ9P7^Q9p;hQ9q;jQ9r;lQ9s;nQ9t8wQ:X;qQ:b;rQ;z<YQ<W<bQ<X<cQ<d<fR<e<gnpOXst!Z#c%j&m&o&p&r,h,m1w1zQ!fPS#eZ#nQ&w!`U'c!o5Y7wQ'y#RQ(|#{Q)m$mS,a&f&iQ,f&jQ,s&vQ,x'OQ-[']Q.p(zQ/Q)nQ0b+SQ0i+^Q1s,eQ2f-^Q2|.[Q3s.{Q4h0[Q5a1_Q5r1oQ5s1pQ5w1rQ5y1tQ6O1|Q6f3PQ6{3pQ7{5dQ8X5tQ8Y5uQ8[5xQ8l6jQ9]7|R9g8]#WcOPXZst!Z!`!o#c#n#{%j&f&i&j&m&o&p&r&v'O'](z+S+^,e,h,m-^.[0[1_1o1p1r1t1w1z1|3P5Y5d5t5u5x6j7w7|8]Q#XWQ#dYQ%nuQ%ovS%qw!gS'|#V(PQ(S#YQ(n#tQ(u#xQ(}$OQ)O$PQ)P$QQ)Q$RQ)R$SQ)S$TQ)T$UQ)U$VQ)V$WQ)W$XQ)X$YQ)Z$[Q)^$aQ)b$eW)l$m)n.{3pQ+Z%pQ+o%}S-O'S2]Q-m'mS-r'}-tQ-w(VQ-y(^Q.h(rQ.n(vQ.r:cQ.t:fQ.u:gQ.v:jQ/V)yQ0_+OQ2W,yQ2Z,|Q2k-fQ2r-zQ3Y.lQ3_:kQ3`:lQ3a:mQ3b:nQ3c:oQ3d:pQ3e:qQ3f:rQ3g:sQ3h:tQ3i:uQ3j:vQ3k.sQ3n:{Q3o;YQ3t:wQ4k0aQ4s0qQ6U;ZQ6[2mQ6a2sQ6o3ZQ6p;[Q6y;^Q6z;eQ7r5WQ8a6SQ8e6]Q8n;fQ8t;oQ8u;pQ9k8gQ9{9WQ:S9iQ:e#RR<P<]R#ZWR'U!eY!tQ'Z-Y1[5]S'Q!e-QQ'f!rS'p!u!xS'r!y5_S,}'R'YS-i'g'hQ-k'iQ2b-WR2p-jR(t#wR(w#xQ!fQT-X'Z-Y]!qQ!r'Z-Y1[5]Q#o]R'd:dT#jZ%bS#iZ%bS%hm,dU(a#g#h#kS-}(b(cQ.R(dQ0c+TQ2u.OU2v.P.Q.SS6c2w2xR8h6d`#]W#V#Y%e'}(W+Q-xr#fZm#g#h#k%b(b(c(d+T.O.P.Q.S2w2x6dQ1q,dQ2X,zQ6Q2PQ8`6RT;w'S+RT#`W%eS#_W%eS(O#V(WS(T#Y+QS-P'S+RT-s'}-xT'X!e%fQ$kfR)s$pT)h$k)iR3r.zT*X$x*ZR*a${Q0g+]Q2z.ZQ5`1^Q6h3OQ7z5cQ8k6gQ9Y7yQ9l8jQ9}9[Q:V9nQ:[:OR:_:WnqOXst!Z#c%j&m&o&p&r,h,m1w1zQ&g!VR,]&dtmOXst!U!V!Z#c%j&d&m&o&p&r,h,m1w1zR,d&jT%im,dR1W+|R,[&bQ&Q|R+t&RR+j%{T&k!W&nT&l!W&nT1y,m1z",nodeNames:"⚠ ArithOp ArithOp JSXStartTag LineComment BlockComment Script Hashbang ExportDeclaration export Star as VariableName String Escape from ; default FunctionDeclaration async function VariableDefinition > < TypeParamList TypeDefinition extends ThisType this LiteralType ArithOp Number BooleanLiteral TemplateType InterpolationEnd Interpolation InterpolationStart NullType null VoidType void TypeofType typeof MemberExpression . ?. PropertyName [ TemplateString Escape Interpolation super RegExp ] ArrayExpression Spread , } { ObjectExpression Property async get set PropertyDefinition Block : NewExpression new TypeArgList CompareOp < ) ( ArgList UnaryExpression delete LogicOp BitOp YieldExpression yield AwaitExpression await ParenthesizedExpression ClassExpression class ClassBody MethodDeclaration Decorator @ MemberExpression PrivatePropertyName CallExpression declare Privacy static abstract override PrivatePropertyDefinition PropertyDeclaration readonly accessor Optional TypeAnnotation Equals StaticBlock FunctionExpression ArrowFunction ParamList ParamList ArrayPattern ObjectPattern PatternProperty Privacy readonly Arrow MemberExpression BinaryExpression ArithOp ArithOp ArithOp ArithOp BitOp CompareOp instanceof satisfies in const CompareOp BitOp BitOp BitOp LogicOp LogicOp ConditionalExpression LogicOp LogicOp AssignmentExpression UpdateOp PostfixExpression CallExpression TaggedTemplateExpression DynamicImport import ImportMeta JSXElement JSXSelfCloseEndTag JSXSelfClosingTag JSXIdentifier JSXBuiltin JSXIdentifier JSXNamespacedName JSXMemberExpression JSXSpreadAttribute JSXAttribute JSXAttributeValue JSXEscape JSXEndTag JSXOpenTag JSXFragmentTag JSXText JSXEscape JSXStartCloseTag JSXCloseTag PrefixCast ArrowFunction TypeParamList SequenceExpression KeyofType keyof UniqueType unique ImportType InferredType infer TypeName ParenthesizedType FunctionSignature ParamList NewSignature IndexedType TupleType Label ArrayType ReadonlyType ObjectType MethodType PropertyType IndexSignature PropertyDefinition CallSignature TypePredicate is NewSignature new UnionType LogicOp IntersectionType LogicOp ConditionalType ParameterizedType ClassDeclaration abstract implements type VariableDeclaration let var using TypeAliasDeclaration InterfaceDeclaration interface EnumDeclaration enum EnumBody NamespaceDeclaration namespace module AmbientDeclaration declare GlobalDeclaration global ClassDeclaration ClassBody AmbientFunctionDeclaration ExportGroup VariableName VariableName ImportDeclaration ImportGroup ForStatement for ForSpec ForInSpec ForOfSpec of WhileStatement while WithStatement with DoStatement do IfStatement if else SwitchStatement switch SwitchBody CaseLabel case DefaultLabel TryStatement try CatchClause catch FinallyClause finally ReturnStatement return ThrowStatement throw BreakStatement break ContinueStatement continue DebuggerStatement debugger LabeledStatement ExpressionStatement SingleExpression SingleClassItem",maxTerm:371,context:sO,nodeProps:[["isolate",-8,4,5,13,33,35,48,50,52,""],["group",-26,8,16,18,65,201,205,209,210,212,215,218,228,230,236,238,240,242,245,251,257,259,261,263,265,267,268,"Statement",-32,12,13,28,31,32,38,48,51,52,54,59,67,75,79,81,83,84,106,107,116,117,134,137,139,140,141,142,144,145,164,165,167,"Expression",-23,27,29,33,37,39,41,168,170,172,173,175,176,177,179,180,181,183,184,185,195,197,199,200,"Type",-3,87,99,105,"ClassItem"],["openedBy",22,"<",34,"InterpolationStart",53,"[",57,"{",72,"(",157,"JSXStartCloseTag"],["closedBy",23,">",36,"InterpolationEnd",47,"]",58,"}",73,")",162,"JSXEndTag"]],propSources:[cO],skippedNodes:[0,4,5,271],repeatNodeCount:37,tokenData:"$Fj(CSR!bOX%ZXY+gYZ-yZ[+g[]%Z]^.c^p%Zpq+gqr/mrs3cst:_tuEruvJSvwLkwx! Yxy!'iyz!(sz{!)}{|!,q|}!.O}!O!,q!O!P!/Y!P!Q!9j!Q!R#8g!R![#:v![!]#Gv!]!^#IS!^!_#J^!_!`#Ns!`!a$#_!a!b$(l!b!c$,k!c!}Er!}#O$-u#O#P$/P#P#Q$4h#Q#R$5r#R#SEr#S#T$7P#T#o$8Z#o#p$<k#p#q$=a#q#r$>q#r#s$?}#s$f%Z$f$g+g$g#BYEr#BY#BZ$AX#BZ$ISEr$IS$I_$AX$I_$I|Er$I|$I}$Dd$I}$JO$Dd$JO$JTEr$JT$JU$AX$JU$KVEr$KV$KW$AX$KW&FUEr&FU&FV$AX&FV;'SEr;'S;=`I|<%l?HTEr?HT?HU$AX?HUOEr(n%d_$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z&j&hT$f&jO!^&c!_#o&c#p;'S&c;'S;=`&w<%lO&c&j&zP;=`<%l&c'|'U]$f&j(R!bOY&}YZ&cZw&}wx&cx!^&}!^!_'}!_#O&}#O#P&c#P#o&}#o#p'}#p;'S&};'S;=`(l<%lO&}!b(SU(R!bOY'}Zw'}x#O'}#P;'S'};'S;=`(f<%lO'}!b(iP;=`<%l'}'|(oP;=`<%l&}'[(y]$f&j(OpOY(rYZ&cZr(rrs&cs!^(r!^!_)r!_#O(r#O#P&c#P#o(r#o#p)r#p;'S(r;'S;=`*a<%lO(rp)wU(OpOY)rZr)rs#O)r#P;'S)r;'S;=`*Z<%lO)rp*^P;=`<%l)r'[*dP;=`<%l(r#S*nX(Op(R!bOY*gZr*grs'}sw*gwx)rx#O*g#P;'S*g;'S;=`+Z<%lO*g#S+^P;=`<%l*g(n+dP;=`<%l%Z(CS+rq$f&j(Op(R!b't(;dOX%ZXY+gYZ&cZ[+g[p%Zpq+gqr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p$f%Z$f$g+g$g#BY%Z#BY#BZ+g#BZ$IS%Z$IS$I_+g$I_$JT%Z$JT$JU+g$JU$KV%Z$KV$KW+g$KW&FU%Z&FU&FV+g&FV;'S%Z;'S;=`+a<%l?HT%Z?HT?HU+g?HUO%Z(CS.ST(P#S$f&j'u(;dO!^&c!_#o&c#p;'S&c;'S;=`&w<%lO&c(CS.n_$f&j(Op(R!b'u(;dOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z%#`/x`$f&j!o$Ip(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`0z!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z%#S1V`#t$Id$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`2X!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z%#S2d_#t$Id$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z$/|3l_'}$(n$f&j(R!bOY4kYZ5qZr4krs7nsw4kwx5qx!^4k!^!_8p!_#O4k#O#P5q#P#o4k#o#p8p#p;'S4k;'S;=`:X<%lO4k(^4r_$f&j(R!bOY4kYZ5qZr4krs7nsw4kwx5qx!^4k!^!_8p!_#O4k#O#P5q#P#o4k#o#p8p#p;'S4k;'S;=`:X<%lO4k&z5vX$f&jOr5qrs6cs!^5q!^!_6y!_#o5q#o#p6y#p;'S5q;'S;=`7h<%lO5q&z6jT$a`$f&jO!^&c!_#o&c#p;'S&c;'S;=`&w<%lO&c`6|TOr6yrs7]s;'S6y;'S;=`7b<%lO6y`7bO$a``7eP;=`<%l6y&z7kP;=`<%l5q(^7w]$a`$f&j(R!bOY&}YZ&cZw&}wx&cx!^&}!^!_'}!_#O&}#O#P&c#P#o&}#o#p'}#p;'S&};'S;=`(l<%lO&}!r8uZ(R!bOY8pYZ6yZr8prs9hsw8pwx6yx#O8p#O#P6y#P;'S8p;'S;=`:R<%lO8p!r9oU$a`(R!bOY'}Zw'}x#O'}#P;'S'};'S;=`(f<%lO'}!r:UP;=`<%l8p(^:[P;=`<%l4k#%|:hh$f&j(Op(R!bOY%ZYZ&cZq%Zqr<Srs&}st%ZtuCruw%Zwx(rx!^%Z!^!_*g!_!c%Z!c!}Cr!}#O%Z#O#P&c#P#R%Z#R#SCr#S#T%Z#T#oCr#o#p*g#p$g%Z$g;'SCr;'S;=`El<%lOCr(r<__VS$f&j(Op(R!bOY<SYZ&cZr<Srs=^sw<Swx@nx!^<S!^!_Bm!_#O<S#O#P>`#P#o<S#o#pBm#p;'S<S;'S;=`Cl<%lO<S(Q=g]VS$f&j(R!bOY=^YZ&cZw=^wx>`x!^=^!^!_?q!_#O=^#O#P>`#P#o=^#o#p?q#p;'S=^;'S;=`@h<%lO=^&n>gXVS$f&jOY>`YZ&cZ!^>`!^!_?S!_#o>`#o#p?S#p;'S>`;'S;=`?k<%lO>`S?XSVSOY?SZ;'S?S;'S;=`?e<%lO?SS?hP;=`<%l?S&n?nP;=`<%l>`!f?xWVS(R!bOY?qZw?qwx?Sx#O?q#O#P?S#P;'S?q;'S;=`@b<%lO?q!f@eP;=`<%l?q(Q@kP;=`<%l=^'`@w]VS$f&j(OpOY@nYZ&cZr@nrs>`s!^@n!^!_Ap!_#O@n#O#P>`#P#o@n#o#pAp#p;'S@n;'S;=`Bg<%lO@ntAwWVS(OpOYApZrAprs?Ss#OAp#O#P?S#P;'SAp;'S;=`Ba<%lOAptBdP;=`<%lAp'`BjP;=`<%l@n#WBvYVS(Op(R!bOYBmZrBmrs?qswBmwxApx#OBm#O#P?S#P;'SBm;'S;=`Cf<%lOBm#WCiP;=`<%lBm(rCoP;=`<%l<S#%|C}i$f&j(g!L^(Op(R!bOY%ZYZ&cZr%Zrs&}st%ZtuCruw%Zwx(rx!Q%Z!Q![Cr![!^%Z!^!_*g!_!c%Z!c!}Cr!}#O%Z#O#P&c#P#R%Z#R#SCr#S#T%Z#T#oCr#o#p*g#p$g%Z$g;'SCr;'S;=`El<%lOCr#%|EoP;=`<%lCr(CSFRk$f&j(Op(R!b$Y#t'{&;d([!LYOY%ZYZ&cZr%Zrs&}st%ZtuEruw%Zwx(rx}%Z}!OGv!O!Q%Z!Q![Er![!^%Z!^!_*g!_!c%Z!c!}Er!}#O%Z#O#P&c#P#R%Z#R#SEr#S#T%Z#T#oEr#o#p*g#p$g%Z$g;'SEr;'S;=`I|<%lOEr+dHRk$f&j(Op(R!b$Y#tOY%ZYZ&cZr%Zrs&}st%ZtuGvuw%Zwx(rx}%Z}!OGv!O!Q%Z!Q![Gv![!^%Z!^!_*g!_!c%Z!c!}Gv!}#O%Z#O#P&c#P#R%Z#R#SGv#S#T%Z#T#oGv#o#p*g#p$g%Z$g;'SGv;'S;=`Iv<%lOGv+dIyP;=`<%lGv(CSJPP;=`<%lEr%#SJ_`$f&j(Op(R!b#l$IdOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z%#SKl_$f&j$O$Id(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z&COLva(p&;`$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sv%ZvwM{wx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z%#SNW`$f&j#x$Id(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z$/|! c_(Q$)`$f&j(OpOY!!bYZ!#hZr!!brs!#hsw!!bwx!$xx!^!!b!^!_!%z!_#O!!b#O#P!#h#P#o!!b#o#p!%z#p;'S!!b;'S;=`!'c<%lO!!b'l!!i_$f&j(OpOY!!bYZ!#hZr!!brs!#hsw!!bwx!$xx!^!!b!^!_!%z!_#O!!b#O#P!#h#P#o!!b#o#p!%z#p;'S!!b;'S;=`!'c<%lO!!b&z!#mX$f&jOw!#hwx6cx!^!#h!^!_!$Y!_#o!#h#o#p!$Y#p;'S!#h;'S;=`!$r<%lO!#h`!$]TOw!$Ywx7]x;'S!$Y;'S;=`!$l<%lO!$Y`!$oP;=`<%l!$Y&z!$uP;=`<%l!#h'l!%R]$a`$f&j(OpOY(rYZ&cZr(rrs&cs!^(r!^!_)r!_#O(r#O#P&c#P#o(r#o#p)r#p;'S(r;'S;=`*a<%lO(r!Q!&PZ(OpOY!%zYZ!$YZr!%zrs!$Ysw!%zwx!&rx#O!%z#O#P!$Y#P;'S!%z;'S;=`!']<%lO!%z!Q!&yU$a`(OpOY)rZr)rs#O)r#P;'S)r;'S;=`*Z<%lO)r!Q!'`P;=`<%l!%z'l!'fP;=`<%l!!b(*Q!'t_!k(!b$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z!'l!)O_!jM|$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'+h!*[b$f&j(Op(R!b'|#)d#m$IdOY%ZYZ&cZr%Zrs&}sw%Zwx(rxz%Zz{!+d{!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z%#S!+o`$f&j(Op(R!b#j$IdOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z&-O!,|`$f&j(Op(R!bn&%`OY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z&C[!.Z_!Y&;l$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(CS!/ec$f&j(Op(R!b|'<nOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!O%Z!O!P!0p!P!Q%Z!Q![!3Y![!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z!'d!0ya$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!O%Z!O!P!2O!P!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z!'d!2Z_!XMt$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z$/l!3eg$f&j(Op(R!bo$'|OY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q![!3Y![!^%Z!^!_*g!_!g%Z!g!h!4|!h#O%Z#O#P&c#P#R%Z#R#S!3Y#S#X%Z#X#Y!4|#Y#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z$/l!5Vg$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx{%Z{|!6n|}%Z}!O!6n!O!Q%Z!Q![!8S![!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S!8S#S#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z$/l!6wc$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q![!8S![!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S!8S#S#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z$/l!8_c$f&j(Op(R!bo$'|OY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q![!8S![!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S!8S#S#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(CS!9uf$f&j(Op(R!b#k$IdOY!;ZYZ&cZr!;Zrs!<nsw!;Zwx!Kpxz!;Zz{#,f{!P!;Z!P!Q#-{!Q!^!;Z!^!_#'Z!_!`#5k!`!a#7Q!a!}!;Z!}#O#*}#O#P!Dj#P#o!;Z#o#p#'Z#p;'S!;Z;'S;=`#,`<%lO!;Z(r!;fb$f&j(Op(R!b!USOY!;ZYZ&cZr!;Zrs!<nsw!;Zwx!Kpx!P!;Z!P!Q#%Z!Q!^!;Z!^!_#'Z!_!}!;Z!}#O#*}#O#P!Dj#P#o!;Z#o#p#'Z#p;'S!;Z;'S;=`#,`<%lO!;Z(Q!<w`$f&j(R!b!USOY!<nYZ&cZw!<nwx!=yx!P!<n!P!Q!Eb!Q!^!<n!^!_!GY!_!}!<n!}#O!Ja#O#P!Dj#P#o!<n#o#p!GY#p;'S!<n;'S;=`!Kj<%lO!<n&n!>Q^$f&j!USOY!=yYZ&cZ!P!=y!P!Q!>|!Q!^!=y!^!_!@Y!_!}!=y!}#O!Bw#O#P!Dj#P#o!=y#o#p!@Y#p;'S!=y;'S;=`!E[<%lO!=y&n!?Ta$f&j!USO!^&c!_#Z&c#Z#[!>|#[#]&c#]#^!>|#^#a&c#a#b!>|#b#g&c#g#h!>|#h#i&c#i#j!>|#j#m&c#m#n!>|#n#o&c#p;'S&c;'S;=`&w<%lO&cS!@_X!USOY!@YZ!P!@Y!P!Q!@z!Q!}!@Y!}#O!Ac#O#P!Bb#P;'S!@Y;'S;=`!Bq<%lO!@YS!APU!US#Z#[!@z#]#^!@z#a#b!@z#g#h!@z#i#j!@z#m#n!@zS!AfVOY!AcZ#O!Ac#O#P!A{#P#Q!@Y#Q;'S!Ac;'S;=`!B[<%lO!AcS!BOSOY!AcZ;'S!Ac;'S;=`!B[<%lO!AcS!B_P;=`<%l!AcS!BeSOY!@YZ;'S!@Y;'S;=`!Bq<%lO!@YS!BtP;=`<%l!@Y&n!B|[$f&jOY!BwYZ&cZ!^!Bw!^!_!Ac!_#O!Bw#O#P!Cr#P#Q!=y#Q#o!Bw#o#p!Ac#p;'S!Bw;'S;=`!Dd<%lO!Bw&n!CwX$f&jOY!BwYZ&cZ!^!Bw!^!_!Ac!_#o!Bw#o#p!Ac#p;'S!Bw;'S;=`!Dd<%lO!Bw&n!DgP;=`<%l!Bw&n!DoX$f&jOY!=yYZ&cZ!^!=y!^!_!@Y!_#o!=y#o#p!@Y#p;'S!=y;'S;=`!E[<%lO!=y&n!E_P;=`<%l!=y(Q!Eki$f&j(R!b!USOY&}YZ&cZw&}wx&cx!^&}!^!_'}!_#O&}#O#P&c#P#Z&}#Z#[!Eb#[#]&}#]#^!Eb#^#a&}#a#b!Eb#b#g&}#g#h!Eb#h#i&}#i#j!Eb#j#m&}#m#n!Eb#n#o&}#o#p'}#p;'S&};'S;=`(l<%lO&}!f!GaZ(R!b!USOY!GYZw!GYwx!@Yx!P!GY!P!Q!HS!Q!}!GY!}#O!Ic#O#P!Bb#P;'S!GY;'S;=`!JZ<%lO!GY!f!HZb(R!b!USOY'}Zw'}x#O'}#P#Z'}#Z#[!HS#[#]'}#]#^!HS#^#a'}#a#b!HS#b#g'}#g#h!HS#h#i'}#i#j!HS#j#m'}#m#n!HS#n;'S'};'S;=`(f<%lO'}!f!IhX(R!bOY!IcZw!Icwx!Acx#O!Ic#O#P!A{#P#Q!GY#Q;'S!Ic;'S;=`!JT<%lO!Ic!f!JWP;=`<%l!Ic!f!J^P;=`<%l!GY(Q!Jh^$f&j(R!bOY!JaYZ&cZw!Jawx!Bwx!^!Ja!^!_!Ic!_#O!Ja#O#P!Cr#P#Q!<n#Q#o!Ja#o#p!Ic#p;'S!Ja;'S;=`!Kd<%lO!Ja(Q!KgP;=`<%l!Ja(Q!KmP;=`<%l!<n'`!Ky`$f&j(Op!USOY!KpYZ&cZr!Kprs!=ys!P!Kp!P!Q!L{!Q!^!Kp!^!_!Ns!_!}!Kp!}#O##z#O#P!Dj#P#o!Kp#o#p!Ns#p;'S!Kp;'S;=`#%T<%lO!Kp'`!MUi$f&j(Op!USOY(rYZ&cZr(rrs&cs!^(r!^!_)r!_#O(r#O#P&c#P#Z(r#Z#[!L{#[#](r#]#^!L{#^#a(r#a#b!L{#b#g(r#g#h!L{#h#i(r#i#j!L{#j#m(r#m#n!L{#n#o(r#o#p)r#p;'S(r;'S;=`*a<%lO(rt!NzZ(Op!USOY!NsZr!Nsrs!@Ys!P!Ns!P!Q# m!Q!}!Ns!}#O#!|#O#P!Bb#P;'S!Ns;'S;=`##t<%lO!Nst# tb(Op!USOY)rZr)rs#O)r#P#Z)r#Z#[# m#[#])r#]#^# m#^#a)r#a#b# m#b#g)r#g#h# m#h#i)r#i#j# m#j#m)r#m#n# m#n;'S)r;'S;=`*Z<%lO)rt##RX(OpOY#!|Zr#!|rs!Acs#O#!|#O#P!A{#P#Q!Ns#Q;'S#!|;'S;=`##n<%lO#!|t##qP;=`<%l#!|t##wP;=`<%l!Ns'`#$R^$f&j(OpOY##zYZ&cZr##zrs!Bws!^##z!^!_#!|!_#O##z#O#P!Cr#P#Q!Kp#Q#o##z#o#p#!|#p;'S##z;'S;=`#$}<%lO##z'`#%QP;=`<%l##z'`#%WP;=`<%l!Kp(r#%fk$f&j(Op(R!b!USOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#Z%Z#Z#[#%Z#[#]%Z#]#^#%Z#^#a%Z#a#b#%Z#b#g%Z#g#h#%Z#h#i%Z#i#j#%Z#j#m%Z#m#n#%Z#n#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z#W#'d](Op(R!b!USOY#'ZZr#'Zrs!GYsw#'Zwx!Nsx!P#'Z!P!Q#(]!Q!}#'Z!}#O#)w#O#P!Bb#P;'S#'Z;'S;=`#*w<%lO#'Z#W#(fe(Op(R!b!USOY*gZr*grs'}sw*gwx)rx#O*g#P#Z*g#Z#[#(]#[#]*g#]#^#(]#^#a*g#a#b#(]#b#g*g#g#h#(]#h#i*g#i#j#(]#j#m*g#m#n#(]#n;'S*g;'S;=`+Z<%lO*g#W#*OZ(Op(R!bOY#)wZr#)wrs!Icsw#)wwx#!|x#O#)w#O#P!A{#P#Q#'Z#Q;'S#)w;'S;=`#*q<%lO#)w#W#*tP;=`<%l#)w#W#*zP;=`<%l#'Z(r#+W`$f&j(Op(R!bOY#*}YZ&cZr#*}rs!Jasw#*}wx##zx!^#*}!^!_#)w!_#O#*}#O#P!Cr#P#Q!;Z#Q#o#*}#o#p#)w#p;'S#*};'S;=`#,Y<%lO#*}(r#,]P;=`<%l#*}(r#,cP;=`<%l!;Z(CS#,sb$f&j(Op(R!b'v(;d!USOY!;ZYZ&cZr!;Zrs!<nsw!;Zwx!Kpx!P!;Z!P!Q#%Z!Q!^!;Z!^!_#'Z!_!}!;Z!}#O#*}#O#P!Dj#P#o!;Z#o#p#'Z#p;'S!;Z;'S;=`#,`<%lO!;Z(CS#.W_$f&j(Op(R!bS(;dOY#-{YZ&cZr#-{rs#/Vsw#-{wx#2gx!^#-{!^!_#4f!_#O#-{#O#P#0X#P#o#-{#o#p#4f#p;'S#-{;'S;=`#5e<%lO#-{(Bb#/`]$f&j(R!bS(;dOY#/VYZ&cZw#/Vwx#0Xx!^#/V!^!_#1j!_#O#/V#O#P#0X#P#o#/V#o#p#1j#p;'S#/V;'S;=`#2a<%lO#/V(AO#0`X$f&jS(;dOY#0XYZ&cZ!^#0X!^!_#0{!_#o#0X#o#p#0{#p;'S#0X;'S;=`#1d<%lO#0X(;d#1QSS(;dOY#0{Z;'S#0{;'S;=`#1^<%lO#0{(;d#1aP;=`<%l#0{(AO#1gP;=`<%l#0X(<v#1qW(R!bS(;dOY#1jZw#1jwx#0{x#O#1j#O#P#0{#P;'S#1j;'S;=`#2Z<%lO#1j(<v#2^P;=`<%l#1j(Bb#2dP;=`<%l#/V(Ap#2p]$f&j(OpS(;dOY#2gYZ&cZr#2grs#0Xs!^#2g!^!_#3i!_#O#2g#O#P#0X#P#o#2g#o#p#3i#p;'S#2g;'S;=`#4`<%lO#2g(<U#3pW(OpS(;dOY#3iZr#3irs#0{s#O#3i#O#P#0{#P;'S#3i;'S;=`#4Y<%lO#3i(<U#4]P;=`<%l#3i(Ap#4cP;=`<%l#2g(=h#4oY(Op(R!bS(;dOY#4fZr#4frs#1jsw#4fwx#3ix#O#4f#O#P#0{#P;'S#4f;'S;=`#5_<%lO#4f(=h#5bP;=`<%l#4f(CS#5hP;=`<%l#-{%#W#5xb$f&j$O$Id(Op(R!b!USOY!;ZYZ&cZr!;Zrs!<nsw!;Zwx!Kpx!P!;Z!P!Q#%Z!Q!^!;Z!^!_#'Z!_!}!;Z!}#O#*}#O#P!Dj#P#o!;Z#o#p#'Z#p;'S!;Z;'S;=`#,`<%lO!;Z+h#7_b$W#t$f&j(Op(R!b!USOY!;ZYZ&cZr!;Zrs!<nsw!;Zwx!Kpx!P!;Z!P!Q#%Z!Q!^!;Z!^!_#'Z!_!}!;Z!}#O#*}#O#P!Dj#P#o!;Z#o#p#'Z#p;'S!;Z;'S;=`#,`<%lO!;Z$/l#8rp$f&j(Op(R!bo$'|OY%ZYZ&cZr%Zrs&}sw%Zwx(rx!O%Z!O!P!3Y!P!Q%Z!Q![#:v![!^%Z!^!_*g!_!g%Z!g!h!4|!h#O%Z#O#P&c#P#R%Z#R#S#:v#S#U%Z#U#V#>Q#V#X%Z#X#Y!4|#Y#b%Z#b#c#<v#c#d#AY#d#l%Z#l#m#D[#m#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z$/l#;Rk$f&j(Op(R!bo$'|OY%ZYZ&cZr%Zrs&}sw%Zwx(rx!O%Z!O!P!3Y!P!Q%Z!Q![#:v![!^%Z!^!_*g!_!g%Z!g!h!4|!h#O%Z#O#P&c#P#R%Z#R#S#:v#S#X%Z#X#Y!4|#Y#b%Z#b#c#<v#c#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z$/l#=R_$f&j(Op(R!bo$'|OY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z$/l#>Zd$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q!R#?i!R!S#?i!S!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S#?i#S#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z$/l#?tf$f&j(Op(R!bo$'|OY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q!R#?i!R!S#?i!S!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S#?i#S#b%Z#b#c#<v#c#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z$/l#Acc$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q!Y#Bn!Y!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S#Bn#S#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z$/l#Bye$f&j(Op(R!bo$'|OY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q!Y#Bn!Y!^%Z!^!_*g!_#O%Z#O#P&c#P#R%Z#R#S#Bn#S#b%Z#b#c#<v#c#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z$/l#Deg$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q![#E|![!^%Z!^!_*g!_!c%Z!c!i#E|!i#O%Z#O#P&c#P#R%Z#R#S#E|#S#T%Z#T#Z#E|#Z#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z$/l#FXi$f&j(Op(R!bo$'|OY%ZYZ&cZr%Zrs&}sw%Zwx(rx!Q%Z!Q![#E|![!^%Z!^!_*g!_!c%Z!c!i#E|!i#O%Z#O#P&c#P#R%Z#R#S#E|#S#T%Z#T#Z#E|#Z#b%Z#b#c#<v#c#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z%Gh#HT_!d$b$f&j#|%<f(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z)[#I__`l$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(@^#Jk^g!*v!h'.r(Op(R!b(tSOY*gZr*grs'}sw*gwx)rx!P*g!P!Q#Kg!Q!^*g!^!_#L]!_!`#M}!`#O*g#P;'S*g;'S;=`+Z<%lO*g(n#KpX$h&j(Op(R!bOY*gZr*grs'}sw*gwx)rx#O*g#P;'S*g;'S;=`+Z<%lO*g$Kh#LfZ#n$Id(Op(R!bOY*gZr*grs'}sw*gwx)rx!_*g!_!`#MX!`#O*g#P;'S*g;'S;=`+Z<%lO*g$Kh#MbX$O$Id(Op(R!bOY*gZr*grs'}sw*gwx)rx#O*g#P;'S*g;'S;=`+Z<%lO*g$Kh#NWX#o$Id(Op(R!bOY*gZr*grs'}sw*gwx)rx#O*g#P;'S*g;'S;=`+Z<%lO*g%Gh$ Oa#[%?x$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`0z!`!a$!T!a#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z%#W$!`_#g$Ih$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z%Gh$#nafBf#o$Id$c#|$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`$$s!`!a$%}!a#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z%#S$%O_#o$Id$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z%#S$&Ya#n$Id$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`!a$'_!a#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z%#S$'j`#n$Id$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'+h$(wc(h$Ip$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!O%Z!O!P$*S!P!^%Z!^!_*g!_!a%Z!a!b$+^!b#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z'+`$*__}'#p$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z%#S$+i`$f&j#y$Id(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z#&^$,v_!{!Ln$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(@^$.Q_!P(8n$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(n$/UZ$f&jO!^$/w!^!_$0_!_#i$/w#i#j$0d#j#l$/w#l#m$2V#m#o$/w#o#p$0_#p;'S$/w;'S;=`$4b<%lO$/w(n$0OT^#S$f&jO!^&c!_#o&c#p;'S&c;'S;=`&w<%lO&c#S$0dO^#S(n$0i[$f&jO!Q&c!Q![$1_![!^&c!_!c&c!c!i$1_!i#T&c#T#Z$1_#Z#o&c#o#p$3u#p;'S&c;'S;=`&w<%lO&c(n$1dZ$f&jO!Q&c!Q![$2V![!^&c!_!c&c!c!i$2V!i#T&c#T#Z$2V#Z#o&c#p;'S&c;'S;=`&w<%lO&c(n$2[Z$f&jO!Q&c!Q![$2}![!^&c!_!c&c!c!i$2}!i#T&c#T#Z$2}#Z#o&c#p;'S&c;'S;=`&w<%lO&c(n$3SZ$f&jO!Q&c!Q![$/w![!^&c!_!c&c!c!i$/w!i#T&c#T#Z$/w#Z#o&c#p;'S&c;'S;=`&w<%lO&c#S$3xR!Q![$4R!c!i$4R#T#Z$4R#S$4US!Q![$4R!c!i$4R#T#Z$4R#q#r$0_(n$4eP;=`<%l$/w!2r$4s_!V!+S$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z%#S$5}`#v$Id$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z&,v$7[_$f&j(Op(R!b(X&%WOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(CS$8jk$f&j(Op(R!b'{&;d$[#t([!LYOY%ZYZ&cZr%Zrs&}st%Ztu$8Zuw%Zwx(rx}%Z}!O$:_!O!Q%Z!Q![$8Z![!^%Z!^!_*g!_!c%Z!c!}$8Z!}#O%Z#O#P&c#P#R%Z#R#S$8Z#S#T%Z#T#o$8Z#o#p*g#p$g%Z$g;'S$8Z;'S;=`$<e<%lO$8Z+d$:jk$f&j(Op(R!b$[#tOY%ZYZ&cZr%Zrs&}st%Ztu$:_uw%Zwx(rx}%Z}!O$:_!O!Q%Z!Q![$:_![!^%Z!^!_*g!_!c%Z!c!}$:_!}#O%Z#O#P&c#P#R%Z#R#S$:_#S#T%Z#T#o$:_#o#p*g#p$g%Z$g;'S$:_;'S;=`$<_<%lO$:_+d$<bP;=`<%l$:_(CS$<hP;=`<%l$8Z!5p$<tX![!3l(Op(R!bOY*gZr*grs'}sw*gwx)rx#O*g#P;'S*g;'S;=`+Z<%lO*g&CO$=la(o&;`$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_!`Ka!`#O%Z#O#P&c#P#o%Z#o#p*g#p#q$+^#q;'S%Z;'S;=`+a<%lO%Z%#`$?O_!Z$I`r`$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(r$@Y_!pS$f&j(Op(R!bOY%ZYZ&cZr%Zrs&}sw%Zwx(rx!^%Z!^!_*g!_#O%Z#O#P&c#P#o%Z#o#p*g#p;'S%Z;'S;=`+a<%lO%Z(CS$Aj|$f&j(Op(R!b't(;d$Y#t'{&;d([!LYOX%ZXY+gYZ&cZ[+g[p%Zpq+gqr%Zrs&}st%ZtuEruw%Zwx(rx}%Z}!OGv!O!Q%Z!Q![Er![!^%Z!^!_*g!_!c%Z!c!}Er!}#O%Z#O#P&c#P#R%Z#R#SEr#S#T%Z#T#oEr#o#p*g#p$f%Z$f$g+g$g#BYEr#BY#BZ$AX#BZ$ISEr$IS$I_$AX$I_$JTEr$JT$JU$AX$JU$KVEr$KV$KW$AX$KW&FUEr&FU&FV$AX&FV;'SEr;'S;=`I|<%l?HTEr?HT?HU$AX?HUOEr(CS$Duk$f&j(Op(R!b'u(;d$Y#t'{&;d([!LYOY%ZYZ&cZr%Zrs&}st%ZtuEruw%Zwx(rx}%Z}!OGv!O!Q%Z!Q![Er![!^%Z!^!_*g!_!c%Z!c!}Er!}#O%Z#O#P&c#P#R%Z#R#SEr#S#T%Z#T#oEr#o#p*g#p$g%Z$g;'SEr;'S;=`I|<%lOEr",tokenizers:[oO,aO,hO,2,3,4,5,6,7,8,9,10,11,12,13,rO,new qp("$S~RRtu[#O#Pg#S#T#|~_P#o#pb~gOt~~jVO#i!P#i#j!U#j#l!P#l#m!q#m;'S!P;'S;=`#v<%lO!P~!UO!R~~!XS!Q![!e!c!i!e#T#Z!e#o#p#Z~!hR!Q![!q!c!i!q#T#Z!q~!tR!Q![!}!c!i!}#T#Z!}~#QR!Q![!P!c!i!P#T#Z!P~#^R!Q![#g!c!i#g#T#Z#g~#jS!Q![#g!c!i#g#T#Z#g#q#r!P~#yP;=`<%l!P~$RO(Z~~",141,332),new qp("j~RQYZXz{^~^O'x~~aP!P!Qd~iO'y~~",25,315)],topRules:{Script:[0,6],SingleExpression:[1,269],SingleClassItem:[2,270]},dialects:{jsx:0,ts:14614},dynamicPrecedences:{69:1,79:1,81:1,165:1,193:1},specialized:[{term:319,get:t=>fO[t]||-1},{term:334,get:t=>uO[t]||-1},{term:70,get:t=>dO[t]||-1}],tokenPrec:14638}),OO=[Ed("function ${name}(${params}) {\n\t${}\n}",{label:"function",detail:"definition",type:"keyword"}),Ed("for (let ${index} = 0; ${index} < ${bound}; ${index}++) {\n\t${}\n}",{label:"for",detail:"loop",type:"keyword"}),Ed("for (let ${name} of ${collection}) {\n\t${}\n}",{label:"for",detail:"of loop",type:"keyword"}),Ed("do {\n\t${}\n} while (${})",{label:"do",detail:"loop",type:"keyword"}),Ed("while (${}) {\n\t${}\n}",{label:"while",detail:"loop",type:"keyword"}),Ed("try {\n\t${}\n} catch (${error}) {\n\t${}\n}",{label:"try",detail:"/ catch block",type:"keyword"}),Ed("if (${}) {\n\t${}\n}",{label:"if",detail:"block",type:"keyword"}),Ed("if (${}) {\n\t${}\n} else {\n\t${}\n}",{label:"if",detail:"/ else block",type:"keyword"}),Ed("class ${name} {\n\tconstructor(${params}) {\n\t\t${}\n\t}\n}",{label:"class",detail:"definition",type:"keyword"}),Ed('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),Ed('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],gO=OO.concat([Ed("interface ${name} {\n\t${}\n}",{label:"interface",detail:"definition",type:"keyword"}),Ed("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),Ed("enum ${name} {\n\t${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),mO=new ka,wO=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function vO(t){return(e,i)=>{let n=e.node.getChild("VariableDefinition");return n&&i(n,t),!0}}const bO=["FunctionDeclaration"],yO={FunctionDeclaration:vO("function"),ClassDeclaration:vO("class"),ClassExpression:()=>!0,EnumDeclaration:vO("constant"),TypeAliasDeclaration:vO("type"),NamespaceDeclaration:vO("namespace"),VariableDefinition(t,e){t.matchContext(bO)||e(t,"variable")},TypeDefinition(t,e){e(t,"type")},__proto__:null};function SO(t,e){let i=mO.get(e);if(i)return i;let n=[],s=!0;function r(e,i){let s=t.sliceString(e.from,e.to);n.push({label:s,type:i})}return e.cursor(ra.IncludeAnonymous).iterate((e=>{if(s)s=!1;else if(e.name){let t=yO[e.name];if(t&&t(e,r)||wO.has(e.name))return!1}else if(e.to-e.from>8192){for(let i of SO(t,e.node))n.push(i);return!1}})),mO.set(e,n),n}const xO=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,kO=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName",".","?."];function QO(t){let e=cl(t.state).resolveInner(t.pos,-1);if(kO.indexOf(e.name)>-1)return null;let i="VariableName"==e.name||e.to-e.from<20&&xO.test(t.state.sliceDoc(e.from,e.to));if(!i&&!t.explicit)return null;let n=[];for(let i=e;i;i=i.parent)wO.has(i.name)&&(n=n.concat(SO(t.state.doc,i)));return{options:n,from:i?e.from:t.pos,validFor:xO}}function $O(t,e,i){var n;let s=[];for(;;){let r,o=e.firstChild;if("VariableName"==(null==o?void 0:o.name))return s.push(t(o)),{path:s.reverse(),name:i};if("MemberExpression"!=(null==o?void 0:o.name)||"PropertyName"!=(null===(n=r=o.lastChild)||void 0===n?void 0:n.name))return null;s.push(t(r)),e=o}}function PO(t){let e=e=>t.state.doc.sliceString(e.from,e.to),i=cl(t.state).resolveInner(t.pos,-1);return"PropertyName"==i.name?$O(e,i.parent,e(i)):"."!=i.name&&"?."!=i.name||"MemberExpression"!=i.parent.name?kO.indexOf(i.name)>-1?null:"VariableName"==i.name||i.to-i.from<20&&xO.test(e(i))?{path:[],name:e(i)}:"MemberExpression"==i.name?$O(e,i,""):t.explicit?{path:[],name:""}:null:$O(e,i.parent,"")}const ZO=hl.define({name:"javascript",parser:pO.configure({props:[Cl.add({IfStatement:Dl({except:/^\s*({|else\b)/}),TryStatement:Dl({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:jl,SwitchBody:t=>{let e=t.textAfter,i=/^\s*\}/.test(e),n=/^\s*(case|default)\b/.test(e);return t.baseIndent+(i?0:n?1:2)*t.unit},Block:Wl({closing:"}"}),ArrowFunction:t=>t.baseIndent+t.unit,"TemplateString BlockComment":()=>null,"Statement Property":Dl({except:/^{/}),JSXElement(t){let e=/^\s*<\//.test(t.textAfter);return t.lineIndent(t.node.from)+(e?0:t.unit)},JSXEscape(t){let e=/\s*\}/.test(t.textAfter);return t.lineIndent(t.node.from)+(e?0:t.unit)},"JSXOpenTag JSXSelfClosingTag":t=>t.column(t.node.from)+t.unit}),_l.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":Vl,BlockComment:t=>({from:t.from+2,to:t.to-2})})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),CO={test:t=>/^JSX/.test(t.name),facet:rl({commentTokens:{block:{open:"{/*",close:"*/}"}}})},TO=ZO.configure({dialect:"ts"},"typescript"),AO=ZO.configure({dialect:"jsx",props:[ol.add((t=>t.isTop?[CO]:void 0))]}),RO=ZO.configure({dialect:"jsx ts",props:[ol.add((t=>t.isTop?[CO]:void 0))]},"typescript");let XO=t=>({label:t,type:"keyword"});const YO="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(XO),WO=YO.concat(["declare","implements","private","protected","public"].map(XO));function MO(t,e,i=t.length){for(let n=null==e?void 0:e.firstChild;n;n=n.nextSibling)if("JSXIdentifier"==n.name||"JSXBuiltin"==n.name||"JSXNamespacedName"==n.name||"JSXMemberExpression"==n.name)return t.sliceString(n.from,Math.min(n.to,i));return""}const jO="object"==typeof navigator&&/Android\b/.test(navigator.userAgent),DO=Gs.inputHandler.of(((t,e,i,n,s)=>{if((jO?t.composing:t.compositionStarted)||t.state.readOnly||e!=i||">"!=n&&"/"!=n||!ZO.isActiveAt(t.state,e,-1))return!1;let r=s(),{state:o}=r,a=o.changeByRange((t=>{var e;let i,{head:s}=t,r=cl(o).resolveInner(s-1,-1);if("JSXStartTag"==r.name&&(r=r.parent),o.doc.sliceString(s-1,s)!=n||"JSXAttributeValue"==r.name&&r.to>s);else{if(">"==n&&"JSXFragmentTag"==r.name)return{range:t,changes:{from:s,insert:"</>"}};if("/"==n&&"JSXStartCloseTag"==r.name){let t=r.parent,n=t.parent;if(n&&t.from==s-2&&((i=MO(o.doc,n.firstChild,s))||"JSXFragmentTag"==(null===(e=n.firstChild)||void 0===e?void 0:e.name))){let t=`${i}>`;return{range:Y.cursor(s+t.length,-1),changes:{from:s,insert:t}}}}else if(">"==n){let e=function(t){for(;;){if("JSXOpenTag"==t.name||"JSXSelfClosingTag"==t.name||"JSXFragmentTag"==t.name)return t;if("JSXEscape"==t.name||!t.parent)return null;t=t.parent}}(r);if(e&&!/^\/?>|^<\//.test(o.doc.sliceString(s,s+2))&&(i=MO(o.doc,e,s)))return{range:t,changes:{from:s,insert:`</${i}>`}}}}return{range:t}}));return!a.changes.empty&&(t.dispatch([r,o.update(a,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}));function EO(t,e,i,n){return i.line(t+n.line).from+e+(1==t?n.col-1:-1)}function qO(t,e,i){let n=EO(t.line,t.column,e,i),s={from:n,to:null!=t.endLine&&1!=t.endColumn?EO(t.endLine,t.endColumn,e,i):n,message:t.message,source:t.ruleId?"eslint:"+t.ruleId:"eslint",severity:1==t.severity?"warning":"error"};if(t.fix){let{range:e,text:r}=t.fix,o=e[0]+i.pos-n,a=e[1]+i.pos-n;s.actions=[{name:"fix",apply(t,e){t.dispatch({changes:{from:e+o,to:e+a,insert:r},scrollIntoView:!0})}}]}return s}var _O=Object.freeze({__proto__:null,autoCloseTags:DO,completionPath:PO,esLint:function(t,e){return e||(e={parserOptions:{ecmaVersion:2019,sourceType:"module"},env:{browser:!0,node:!0,es6:!0,es2015:!0,es2017:!0,es2020:!0},rules:{}},t.getRules().forEach(((t,i)=>{t.meta.docs.recommended&&(e.rules[i]=2)}))),i=>{let{state:n}=i,s=[];for(let{from:i,to:r}of ZO.findRegions(n)){let o=n.doc.lineAt(i),a={line:o.number-1,col:i-o.from,pos:i};for(let o of t.verify(n.sliceDoc(i,r),e))s.push(qO(o,n.doc,a))}return s}},javascript:function(t={}){let e=t.jsx?t.typescript?RO:AO:t.typescript?TO:ZO,i=t.typescript?gO.concat(WO):OO.concat(YO);return new yl(e,[ZO.data.of({autocomplete:(n=kO,s=zu(i),t=>{for(let e=cl(t.state).resolveInner(t.pos,-1);e;e=e.parent){if(n.indexOf(e.name)>-1)return null;if(e.type.isTop)break}return s(t)})}),ZO.data.of({autocomplete:QO}),t.jsx?DO:[]]);var n,s},javascriptLanguage:ZO,jsxLanguage:AO,localCompletionSource:QO,scopeCompletionSource:function(t){let e=new Map;return i=>{let n=PO(i);if(!n)return null;let s=t;for(let t of n.path)if(s=s[t],!s)return null;let r=e.get(s);return r||e.set(s,r=function(t,e){let i=[],n=new Set;for(let s=0;;s++){for(let r of(Object.getOwnPropertyNames||Object.keys)(t)){if(!/^[a-zA-Z_$\xaa-\uffdc][\w$\xaa-\uffdc]*$/.test(r)||n.has(r))continue;let o;n.add(r);try{o=t[r]}catch(t){continue}i.push({label:r,type:"function"==typeof o?/^[A-Z]/.test(r)?"class":e?"function":"method":e?"variable":"property",boost:-s})}let r=Object.getPrototypeOf(t);if(!r)return i;t=r}}(s,!n.path.length)),{from:i.pos-n.name.length,options:r,validFor:xO}}},snippets:OO,tsxLanguage:RO,typescriptLanguage:TO,typescriptSnippets:gO});return t.codemirror=Tp,t.codemirrorLangJavascript=_O,t.codemirrorLanguage=cc,t.codemirrorState=Bt,t.codemirrorView=No,t.lezerHighlight=nl,t}({});
diff --git a/devtools/client/shared/sourceeditor/codemirror6/index.mjs b/devtools/client/shared/sourceeditor/codemirror6/index.mjs
new file mode 100644
index 0000000000..a1a03124ce
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror6/index.mjs
@@ -0,0 +1,22 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+import * as codemirror from "codemirror";
+import * as codemirrorView from "@codemirror/view";
+import * as codemirrorState from "@codemirror/state";
+import * as codemirrorLanguage from "@codemirror/language";
+import * as codemirrorLangJavascript from "@codemirror/lang-javascript";
+import * as lezerHighlight from "@lezer/highlight";
+
+// XXX When adding new exports, you need to update the codemirror6.bundle.js file,
+// running `npm install && npm run build-cm6` from the devtools/client/shared/sourceeditor folder
+
+export {
+ codemirror,
+ codemirrorView,
+ codemirrorState,
+ codemirrorLanguage,
+ codemirrorLangJavascript,
+ lezerHighlight,
+};
diff --git a/devtools/client/shared/sourceeditor/codemirror6/moz.build b/devtools/client/shared/sourceeditor/codemirror6/moz.build
new file mode 100644
index 0000000000..4d66cfabea
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/codemirror6/moz.build
@@ -0,0 +1,12 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+DevToolsModules(
+ "codemirror6.bundle.js",
+)
+
+with Files("**"):
+ BUG_COMPONENT = ("DevTools", "Source Editor")
diff --git a/devtools/client/shared/sourceeditor/css-autocompleter.js b/devtools/client/shared/sourceeditor/css-autocompleter.js
new file mode 100644
index 0000000000..7db3cbbc0f
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/css-autocompleter.js
@@ -0,0 +1,1248 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+const {
+ cssTokenizer,
+ cssTokenizerWithLineColumn,
+} = require("resource://devtools/shared/css/parsing-utils.js");
+
+/**
+ * Here is what this file (+ css-parsing-utils.js) do.
+ *
+ * The main objective here is to provide as much suggestions to the user editing
+ * a stylesheet in Style Editor. The possible things that can be suggested are:
+ * - CSS property names
+ * - CSS property values
+ * - CSS Selectors
+ * - Some other known CSS keywords
+ *
+ * Gecko provides a list of both property names and their corresponding values.
+ * We take out a list of matching selectors using the Inspector actor's
+ * `getSuggestionsForQuery` method. Now the only thing is to parse the CSS being
+ * edited by the user, figure out what token or word is being written and last
+ * but the most difficult, what is being edited.
+ *
+ * The file 'css-parsing-utils' helps to convert the CSS into meaningful tokens,
+ * each having a certain type associated with it. These tokens help us to figure
+ * out the currently edited word and to write a CSS state machine to figure out
+ * what the user is currently editing. By that, I mean, whether he is editing a
+ * selector or a property or a value, or even fine grained information like an
+ * id in the selector.
+ *
+ * The `resolveState` method iterated over the tokens spitted out by the
+ * tokenizer, using switch cases, follows a state machine logic and finally
+ * figures out these informations:
+ * - The state of the CSS at the cursor (one out of CSS_STATES)
+ * - The current token that is being edited `cmpleting`
+ * - If the state is "selector", the selector state (one of SELECTOR_STATES)
+ * - If the state is "selector", the current selector till the cursor
+ * - If the state is "value", the corresponding property name
+ *
+ * In case of "value" and "property" states, we simply use the information
+ * provided by Gecko to filter out the possible suggestions.
+ * For "selector" state, we request the Inspector actor to query the page DOM
+ * and filter out the possible suggestions.
+ * For "media" and "keyframes" state, the only possible suggestions for now are
+ * "media" and "keyframes" respectively, although "media" can have suggestions
+ * like "max-width", "orientation" etc. Similarly "value" state can also have
+ * much better logical suggestions if we fine grain identify a sub state just
+ * like we do for the "selector" state.
+ */
+
+// Autocompletion types.
+
+const CSS_STATES = {
+ null: "null",
+ property: "property", // foo { bar|: … }
+ value: "value", // foo {bar: baz|}
+ selector: "selector", // f| {bar: baz}
+ media: "media", // @med| , or , @media scr| { }
+ keyframes: "keyframes", // @keyf|
+ frame: "frame", // @keyframs foobar { t|
+};
+
+const SELECTOR_STATES = {
+ null: "null",
+ id: "id", // #f|
+ class: "class", // #foo.b|
+ tag: "tag", // fo|
+ pseudo: "pseudo", // foo:|
+ attribute: "attribute", // foo[b|
+ value: "value", // foo[bar=b|
+};
+
+/**
+ * Constructor for the autocompletion object.
+ *
+ * @param options {Object} An options object containing the following options:
+ * - walker {Object} The object used for query selecting from the current
+ * target's DOM.
+ * - maxEntries {Number} Maximum selectors suggestions to display.
+ * - cssProperties {Object} The database of CSS properties.
+ */
+function CSSCompleter(options = {}) {
+ this.walker = options.walker;
+ this.maxEntries = options.maxEntries || 15;
+ this.cssProperties = options.cssProperties;
+
+ this.propertyNames = this.cssProperties.getNames().sort();
+
+ // Array containing the [line, ch, scopeStack] for the locations where the
+ // CSS state is "null"
+ this.nullStates = [];
+}
+
+CSSCompleter.prototype = {
+ /**
+ * Returns a list of suggestions based on the caret position.
+ *
+ * @param source {String} String of the source code.
+ * @param caret {Object} Cursor location with line and ch properties.
+ *
+ * @returns [{object}] A sorted list of objects containing the following
+ * peroperties:
+ * - label {String} Full keyword for the suggestion
+ * - preLabel {String} Already entered part of the label
+ */
+ complete(source, caret) {
+ // Getting the context from the caret position.
+ if (!this.resolveState(source, caret)) {
+ // We couldn't resolve the context, we won't be able to complete.
+ return Promise.resolve([]);
+ }
+
+ // Properly suggest based on the state.
+ switch (this.state) {
+ case CSS_STATES.property:
+ return this.completeProperties(this.completing);
+
+ case CSS_STATES.value:
+ return this.completeValues(this.propertyName, this.completing);
+
+ case CSS_STATES.selector:
+ return this.suggestSelectors();
+
+ case CSS_STATES.media:
+ case CSS_STATES.keyframes:
+ if ("media".startsWith(this.completing)) {
+ return Promise.resolve([
+ {
+ label: "media",
+ preLabel: this.completing,
+ text: "media",
+ },
+ ]);
+ } else if ("keyframes".startsWith(this.completing)) {
+ return Promise.resolve([
+ {
+ label: "keyframes",
+ preLabel: this.completing,
+ text: "keyframes",
+ },
+ ]);
+ }
+ }
+ return Promise.resolve([]);
+ },
+
+ /**
+ * Resolves the state of CSS at the cursor location. This method implements a
+ * custom written CSS state machine. The various switch statements provide the
+ * transition rules for the state. It also finds out various informatino about
+ * the nearby CSS like the property name being completed, the complete
+ * selector, etc.
+ *
+ * @param source {String} String of the source code.
+ * @param caret {Object} Cursor location with line and ch properties.
+ *
+ * @returns CSS_STATE
+ * One of CSS_STATE enum or null if the state cannot be resolved.
+ */
+ // eslint-disable-next-line complexity
+ resolveState(source, { line, ch }) {
+ // Function to return the last element of an array
+ const peek = arr => arr[arr.length - 1];
+ // _state can be one of CSS_STATES;
+ let _state = CSS_STATES.null;
+ let selector = "";
+ let selectorState = SELECTOR_STATES.null;
+ let propertyName = null;
+ let scopeStack = [];
+ let selectors = [];
+
+ // Fetch the closest null state line, ch from cached null state locations
+ const matchedStateIndex = this.findNearestNullState(line);
+ if (matchedStateIndex > -1) {
+ const state = this.nullStates[matchedStateIndex];
+ line -= state[0];
+ if (line == 0) {
+ ch -= state[1];
+ }
+ source = source.split("\n").slice(state[0]);
+ source[0] = source[0].slice(state[1]);
+ source = source.join("\n");
+ scopeStack = [...state[2]];
+ this.nullStates.length = matchedStateIndex + 1;
+ } else {
+ this.nullStates = [];
+ }
+ const tokens = cssTokenizerWithLineColumn(source);
+ const tokIndex = tokens.length - 1;
+ if (
+ tokIndex >= 0 &&
+ (tokens[tokIndex].loc.end.line < line ||
+ (tokens[tokIndex].loc.end.line === line &&
+ tokens[tokIndex].loc.end.column < ch))
+ ) {
+ // If the last token ends before the cursor location, we didn't
+ // tokenize it correctly. This special case can happen if the
+ // final token is a comment.
+ return null;
+ }
+
+ let cursor = 0;
+ // This will maintain a stack of paired elements like { & }, @m & }, : & ;
+ // etc
+ let token = null;
+ let selectorBeforeNot = null;
+ while (cursor <= tokIndex && (token = tokens[cursor++])) {
+ switch (_state) {
+ case CSS_STATES.property:
+ // From CSS_STATES.property, we can either go to CSS_STATES.value
+ // state when we hit the first ':' or CSS_STATES.selector if "}" is
+ // reached.
+ if (token.tokenType === "symbol") {
+ switch (token.text) {
+ case ":":
+ scopeStack.push(":");
+ if (tokens[cursor - 2].tokenType != "whitespace") {
+ propertyName = tokens[cursor - 2].text;
+ } else {
+ propertyName = tokens[cursor - 3].text;
+ }
+ _state = CSS_STATES.value;
+ break;
+
+ case "}":
+ if (/[{f]/.test(peek(scopeStack))) {
+ const popped = scopeStack.pop();
+ if (popped == "f") {
+ _state = CSS_STATES.frame;
+ } else {
+ selector = "";
+ selectors = [];
+ _state = CSS_STATES.null;
+ }
+ }
+ break;
+ }
+ }
+ break;
+
+ case CSS_STATES.value:
+ // From CSS_STATES.value, we can go to one of CSS_STATES.property,
+ // CSS_STATES.frame, CSS_STATES.selector and CSS_STATES.null
+ if (token.tokenType === "symbol") {
+ switch (token.text) {
+ case ";":
+ if (/[:]/.test(peek(scopeStack))) {
+ scopeStack.pop();
+ _state = CSS_STATES.property;
+ }
+ break;
+
+ case "}":
+ if (peek(scopeStack) == ":") {
+ scopeStack.pop();
+ }
+
+ if (/[{f]/.test(peek(scopeStack))) {
+ const popped = scopeStack.pop();
+ if (popped == "f") {
+ _state = CSS_STATES.frame;
+ } else {
+ selector = "";
+ selectors = [];
+ _state = CSS_STATES.null;
+ }
+ }
+ break;
+ }
+ }
+ break;
+
+ case CSS_STATES.selector:
+ // From CSS_STATES.selector, we can only go to CSS_STATES.property
+ // when we hit "{"
+ if (token.tokenType === "symbol" && token.text == "{") {
+ scopeStack.push("{");
+ _state = CSS_STATES.property;
+ selectors.push(selector);
+ selector = "";
+ break;
+ }
+
+ switch (selectorState) {
+ case SELECTOR_STATES.id:
+ case SELECTOR_STATES.class:
+ case SELECTOR_STATES.tag:
+ switch (token.tokenType) {
+ case "hash":
+ case "id":
+ selectorState = SELECTOR_STATES.id;
+ selector += "#" + token.text;
+ break;
+
+ case "symbol":
+ if (token.text == ".") {
+ selectorState = SELECTOR_STATES.class;
+ selector += ".";
+ if (
+ cursor <= tokIndex &&
+ tokens[cursor].tokenType == "ident"
+ ) {
+ token = tokens[cursor++];
+ selector += token.text;
+ }
+ } else if (token.text == "#") {
+ selectorState = SELECTOR_STATES.id;
+ selector += "#";
+ } else if (/[>~+]/.test(token.text)) {
+ selectorState = SELECTOR_STATES.null;
+ selector += token.text;
+ } else if (token.text == ",") {
+ selectorState = SELECTOR_STATES.null;
+ selectors.push(selector);
+ selector = "";
+ } else if (token.text == ":") {
+ selectorState = SELECTOR_STATES.pseudo;
+ selector += ":";
+ if (cursor > tokIndex) {
+ break;
+ }
+
+ token = tokens[cursor++];
+ switch (token.tokenType) {
+ case "function":
+ if (token.text == "not") {
+ selectorBeforeNot = selector;
+ selector = "";
+ scopeStack.push("(");
+ } else {
+ selector += token.text + "(";
+ }
+ selectorState = SELECTOR_STATES.null;
+ break;
+
+ case "ident":
+ selector += token.text;
+ break;
+ }
+ } else if (token.text == "[") {
+ selectorState = SELECTOR_STATES.attribute;
+ scopeStack.push("[");
+ selector += "[";
+ } else if (token.text == ")") {
+ if (peek(scopeStack) == "(") {
+ scopeStack.pop();
+ selector = selectorBeforeNot + "not(" + selector + ")";
+ selectorBeforeNot = null;
+ } else {
+ selector += ")";
+ }
+ selectorState = SELECTOR_STATES.null;
+ }
+ break;
+
+ case "whitespace":
+ selectorState = SELECTOR_STATES.null;
+ selector && (selector += " ");
+ break;
+ }
+ break;
+
+ case SELECTOR_STATES.null:
+ // From SELECTOR_STATES.null state, we can go to one of
+ // SELECTOR_STATES.id, SELECTOR_STATES.class or
+ // SELECTOR_STATES.tag
+ switch (token.tokenType) {
+ case "hash":
+ case "id":
+ selectorState = SELECTOR_STATES.id;
+ selector += "#" + token.text;
+ break;
+
+ case "ident":
+ selectorState = SELECTOR_STATES.tag;
+ selector += token.text;
+ break;
+
+ case "symbol":
+ if (token.text == ".") {
+ selectorState = SELECTOR_STATES.class;
+ selector += ".";
+ if (
+ cursor <= tokIndex &&
+ tokens[cursor].tokenType == "ident"
+ ) {
+ token = tokens[cursor++];
+ selector += token.text;
+ }
+ } else if (token.text == "#") {
+ selectorState = SELECTOR_STATES.id;
+ selector += "#";
+ } else if (token.text == "*") {
+ selectorState = SELECTOR_STATES.tag;
+ selector += "*";
+ } else if (/[>~+]/.test(token.text)) {
+ selector += token.text;
+ } else if (token.text == ",") {
+ selectorState = SELECTOR_STATES.null;
+ selectors.push(selector);
+ selector = "";
+ } else if (token.text == ":") {
+ selectorState = SELECTOR_STATES.pseudo;
+ selector += ":";
+ if (cursor > tokIndex) {
+ break;
+ }
+
+ token = tokens[cursor++];
+ switch (token.tokenType) {
+ case "function":
+ if (token.text == "not") {
+ selectorBeforeNot = selector;
+ selector = "";
+ scopeStack.push("(");
+ } else {
+ selector += token.text + "(";
+ }
+ selectorState = SELECTOR_STATES.null;
+ break;
+
+ case "ident":
+ selector += token.text;
+ break;
+ }
+ } else if (token.text == "[") {
+ selectorState = SELECTOR_STATES.attribute;
+ scopeStack.push("[");
+ selector += "[";
+ } else if (token.text == ")") {
+ if (peek(scopeStack) == "(") {
+ scopeStack.pop();
+ selector = selectorBeforeNot + "not(" + selector + ")";
+ selectorBeforeNot = null;
+ } else {
+ selector += ")";
+ }
+ selectorState = SELECTOR_STATES.null;
+ }
+ break;
+
+ case "whitespace":
+ selector && (selector += " ");
+ break;
+ }
+ break;
+
+ case SELECTOR_STATES.pseudo:
+ switch (token.tokenType) {
+ case "symbol":
+ if (/[>~+]/.test(token.text)) {
+ selectorState = SELECTOR_STATES.null;
+ selector += token.text;
+ } else if (token.text == ",") {
+ selectorState = SELECTOR_STATES.null;
+ selectors.push(selector);
+ selector = "";
+ } else if (token.text == ":") {
+ selectorState = SELECTOR_STATES.pseudo;
+ selector += ":";
+ if (cursor > tokIndex) {
+ break;
+ }
+
+ token = tokens[cursor++];
+ switch (token.tokenType) {
+ case "function":
+ if (token.text == "not") {
+ selectorBeforeNot = selector;
+ selector = "";
+ scopeStack.push("(");
+ } else {
+ selector += token.text + "(";
+ }
+ selectorState = SELECTOR_STATES.null;
+ break;
+
+ case "ident":
+ selector += token.text;
+ break;
+ }
+ } else if (token.text == "[") {
+ selectorState = SELECTOR_STATES.attribute;
+ scopeStack.push("[");
+ selector += "[";
+ }
+ break;
+
+ case "whitespace":
+ selectorState = SELECTOR_STATES.null;
+ selector && (selector += " ");
+ break;
+ }
+ break;
+
+ case SELECTOR_STATES.attribute:
+ switch (token.tokenType) {
+ case "symbol":
+ if (/[~|^$*]/.test(token.text)) {
+ selector += token.text;
+ token = tokens[cursor++];
+ } else if (token.text == "=") {
+ selectorState = SELECTOR_STATES.value;
+ selector += token.text;
+ } else if (token.text == "]") {
+ if (peek(scopeStack) == "[") {
+ scopeStack.pop();
+ }
+
+ selectorState = SELECTOR_STATES.null;
+ selector += "]";
+ }
+ break;
+
+ case "ident":
+ case "string":
+ selector += token.text;
+ break;
+
+ case "whitespace":
+ selector && (selector += " ");
+ break;
+ }
+ break;
+
+ case SELECTOR_STATES.value:
+ switch (token.tokenType) {
+ case "string":
+ case "ident":
+ selector += token.text;
+ break;
+
+ case "symbol":
+ if (token.text == "]") {
+ if (peek(scopeStack) == "[") {
+ scopeStack.pop();
+ }
+
+ selectorState = SELECTOR_STATES.null;
+ selector += "]";
+ }
+ break;
+
+ case "whitespace":
+ selector && (selector += " ");
+ break;
+ }
+ break;
+ }
+ break;
+
+ case CSS_STATES.null:
+ // From CSS_STATES.null state, we can go to either CSS_STATES.media or
+ // CSS_STATES.selector.
+ switch (token.tokenType) {
+ case "hash":
+ case "id":
+ selectorState = SELECTOR_STATES.id;
+ selector = "#" + token.text;
+ _state = CSS_STATES.selector;
+ break;
+
+ case "ident":
+ selectorState = SELECTOR_STATES.tag;
+ selector = token.text;
+ _state = CSS_STATES.selector;
+ break;
+
+ case "symbol":
+ if (token.text == ".") {
+ selectorState = SELECTOR_STATES.class;
+ selector = ".";
+ _state = CSS_STATES.selector;
+ if (cursor <= tokIndex && tokens[cursor].tokenType == "ident") {
+ token = tokens[cursor++];
+ selector += token.text;
+ }
+ } else if (token.text == "#") {
+ selectorState = SELECTOR_STATES.id;
+ selector = "#";
+ _state = CSS_STATES.selector;
+ } else if (token.text == "*") {
+ selectorState = SELECTOR_STATES.tag;
+ selector = "*";
+ _state = CSS_STATES.selector;
+ } else if (token.text == ":") {
+ _state = CSS_STATES.selector;
+ selectorState = SELECTOR_STATES.pseudo;
+ selector += ":";
+ if (cursor > tokIndex) {
+ break;
+ }
+
+ token = tokens[cursor++];
+ switch (token.tokenType) {
+ case "function":
+ if (token.text == "not") {
+ selectorBeforeNot = selector;
+ selector = "";
+ scopeStack.push("(");
+ } else {
+ selector += token.text + "(";
+ }
+ selectorState = SELECTOR_STATES.null;
+ break;
+
+ case "ident":
+ selector += token.text;
+ break;
+ }
+ } else if (token.text == "[") {
+ _state = CSS_STATES.selector;
+ selectorState = SELECTOR_STATES.attribute;
+ scopeStack.push("[");
+ selector += "[";
+ } else if (token.text == "}") {
+ if (peek(scopeStack) == "@m") {
+ scopeStack.pop();
+ }
+ }
+ break;
+
+ case "at":
+ _state = token.text.startsWith("m")
+ ? CSS_STATES.media
+ : CSS_STATES.keyframes;
+ break;
+ }
+ break;
+
+ case CSS_STATES.media:
+ // From CSS_STATES.media, we can only go to CSS_STATES.null state when
+ // we hit the first '{'
+ if (token.tokenType == "symbol" && token.text == "{") {
+ scopeStack.push("@m");
+ _state = CSS_STATES.null;
+ }
+ break;
+
+ case CSS_STATES.keyframes:
+ // From CSS_STATES.keyframes, we can only go to CSS_STATES.frame state
+ // when we hit the first '{'
+ if (token.tokenType == "symbol" && token.text == "{") {
+ scopeStack.push("@k");
+ _state = CSS_STATES.frame;
+ }
+ break;
+
+ case CSS_STATES.frame:
+ // From CSS_STATES.frame, we can either go to CSS_STATES.property
+ // state when we hit the first '{' or to CSS_STATES.selector when we
+ // hit '}'
+ if (token.tokenType == "symbol") {
+ if (token.text == "{") {
+ scopeStack.push("f");
+ _state = CSS_STATES.property;
+ } else if (token.text == "}") {
+ if (peek(scopeStack) == "@k") {
+ scopeStack.pop();
+ }
+
+ _state = CSS_STATES.null;
+ }
+ }
+ break;
+ }
+ if (_state == CSS_STATES.null) {
+ if (!this.nullStates.length) {
+ this.nullStates.push([
+ token.loc.end.line,
+ token.loc.end.column,
+ [...scopeStack],
+ ]);
+ continue;
+ }
+ let tokenLine = token.loc.end.line;
+ const tokenCh = token.loc.end.column;
+ if (tokenLine == 0) {
+ continue;
+ }
+ if (matchedStateIndex > -1) {
+ tokenLine += this.nullStates[matchedStateIndex][0];
+ }
+ this.nullStates.push([tokenLine, tokenCh, [...scopeStack]]);
+ }
+ }
+ this.state = _state;
+ this.propertyName = _state == CSS_STATES.value ? propertyName : null;
+ this.selectorState = _state == CSS_STATES.selector ? selectorState : null;
+ this.selectorBeforeNot =
+ selectorBeforeNot == null ? null : selectorBeforeNot;
+ if (token) {
+ selector = selector.slice(0, selector.length + token.loc.end.column - ch);
+ this.selector = selector;
+ } else {
+ this.selector = "";
+ }
+ this.selectors = selectors;
+
+ if (token && token.tokenType != "whitespace") {
+ let text;
+ if (token.tokenType == "dimension" || !token.text) {
+ text = source.substring(token.startOffset, token.endOffset);
+ } else {
+ text = token.text;
+ }
+ this.completing = text
+ .slice(0, ch - token.loc.start.column)
+ .replace(/^[.#]$/, "");
+ } else {
+ this.completing = "";
+ }
+ // Special case the situation when the user just entered ":" after typing a
+ // property name.
+ if (this.completing == ":" && _state == CSS_STATES.value) {
+ this.completing = "";
+ }
+
+ // Special check for !important; case.
+ if (
+ token &&
+ tokens[cursor - 2] &&
+ tokens[cursor - 2].text == "!" &&
+ this.completing == "important".slice(0, this.completing.length)
+ ) {
+ this.completing = "!" + this.completing;
+ }
+ return _state;
+ },
+
+ /**
+ * Queries the DOM Walker actor for suggestions regarding the selector being
+ * completed
+ */
+ suggestSelectors() {
+ const walker = this.walker;
+ if (!walker) {
+ return Promise.resolve([]);
+ }
+
+ let query = this.selector;
+ // Even though the selector matched atleast one node, there is still
+ // possibility of suggestions.
+ switch (this.selectorState) {
+ case SELECTOR_STATES.null:
+ if (this.completing === ",") {
+ return Promise.resolve([]);
+ }
+
+ query += "*";
+ break;
+
+ case SELECTOR_STATES.tag:
+ query = query.slice(0, query.length - this.completing.length);
+ break;
+
+ case SELECTOR_STATES.id:
+ case SELECTOR_STATES.class:
+ case SELECTOR_STATES.pseudo:
+ if (/^[.:#]$/.test(this.completing)) {
+ query = query.slice(0, query.length - this.completing.length);
+ this.completing = "";
+ } else {
+ query = query.slice(0, query.length - this.completing.length - 1);
+ }
+ break;
+ }
+
+ if (
+ /[\s+>~]$/.test(query) &&
+ this.selectorState != SELECTOR_STATES.attribute &&
+ this.selectorState != SELECTOR_STATES.value
+ ) {
+ query += "*";
+ }
+
+ // Set the values that this request was supposed to suggest to.
+ this._currentQuery = query;
+ return walker
+ .getSuggestionsForQuery(query, this.completing, this.selectorState)
+ .then(result => this.prepareSelectorResults(result));
+ },
+
+ /**
+ * Prepares the selector suggestions returned by the walker actor.
+ */
+ prepareSelectorResults(result) {
+ if (this._currentQuery != result.query) {
+ return [];
+ }
+
+ result = result.suggestions;
+ const query = this.selector;
+ const completion = [];
+ for (let [value, count, state] of result) {
+ switch (this.selectorState) {
+ case SELECTOR_STATES.id:
+ case SELECTOR_STATES.class:
+ case SELECTOR_STATES.pseudo:
+ if (/^[.:#]$/.test(this.completing)) {
+ value =
+ query.slice(0, query.length - this.completing.length) + value;
+ } else {
+ value =
+ query.slice(0, query.length - this.completing.length - 1) + value;
+ }
+ break;
+
+ case SELECTOR_STATES.tag:
+ value = query.slice(0, query.length - this.completing.length) + value;
+ break;
+
+ case SELECTOR_STATES.null:
+ value = query + value;
+ break;
+
+ default:
+ value = query.slice(0, query.length - this.completing.length) + value;
+ }
+
+ const item = {
+ label: value,
+ preLabel: query,
+ text: value,
+ score: count,
+ };
+
+ // In case the query's state is tag and the item's state is id or class
+ // adjust the preLabel
+ if (
+ this.selectorState === SELECTOR_STATES.tag &&
+ state === SELECTOR_STATES.class
+ ) {
+ item.preLabel = "." + item.preLabel;
+ }
+ if (
+ this.selectorState === SELECTOR_STATES.tag &&
+ state === SELECTOR_STATES.id
+ ) {
+ item.preLabel = "#" + item.preLabel;
+ }
+
+ completion.push(item);
+
+ if (completion.length > this.maxEntries - 1) {
+ break;
+ }
+ }
+ return completion;
+ },
+
+ /**
+ * Returns CSS property name suggestions based on the input.
+ *
+ * @param startProp {String} Initial part of the property being completed.
+ */
+ completeProperties(startProp) {
+ const finalList = [];
+ if (!startProp) {
+ return Promise.resolve(finalList);
+ }
+
+ const length = this.propertyNames.length;
+ let i = 0,
+ count = 0;
+ for (; i < length && count < this.maxEntries; i++) {
+ if (this.propertyNames[i].startsWith(startProp)) {
+ count++;
+ const propName = this.propertyNames[i];
+ finalList.push({
+ preLabel: startProp,
+ label: propName,
+ text: propName + ": ",
+ });
+ } else if (this.propertyNames[i] > startProp) {
+ // We have crossed all possible matches alphabetically.
+ break;
+ }
+ }
+ return Promise.resolve(finalList);
+ },
+
+ /**
+ * Returns CSS value suggestions based on the corresponding property.
+ *
+ * @param propName {String} The property to which the value being completed
+ * belongs.
+ * @param startValue {String} Initial part of the value being completed.
+ */
+ completeValues(propName, startValue) {
+ const finalList = [];
+ const list = ["!important;", ...this.cssProperties.getValues(propName)];
+ // If there is no character being completed, we are showing an initial list
+ // of possible values. Skipping '!important' in this case.
+ if (!startValue) {
+ list.splice(0, 1);
+ }
+
+ const length = list.length;
+ let i = 0,
+ count = 0;
+ for (; i < length && count < this.maxEntries; i++) {
+ if (list[i].startsWith(startValue)) {
+ count++;
+ const value = list[i];
+ finalList.push({
+ preLabel: startValue,
+ label: value,
+ text: value,
+ });
+ } else if (list[i] > startValue) {
+ // We have crossed all possible matches alphabetically.
+ break;
+ }
+ }
+ return Promise.resolve(finalList);
+ },
+
+ /**
+ * A biased binary search in a sorted array where the middle element is
+ * calculated based on the values at the lower and the upper index in each
+ * iteration.
+ *
+ * This method returns the index of the closest null state from the passed
+ * `line` argument. Once we have the closest null state, we can start applying
+ * the state machine logic from that location instead of the absolute starting
+ * of the CSS source. This speeds up the tokenizing and the state machine a
+ * lot while using autocompletion at high line numbers in a CSS source.
+ */
+ findNearestNullState(line) {
+ const arr = this.nullStates;
+ let high = arr.length - 1;
+ let low = 0;
+ let target = 0;
+
+ if (high < 0) {
+ return -1;
+ }
+ if (arr[high][0] <= line) {
+ return high;
+ }
+ if (arr[low][0] > line) {
+ return -1;
+ }
+
+ while (high > low) {
+ if (arr[low][0] <= line && arr[low[0] + 1] > line) {
+ return low;
+ }
+ if (arr[high][0] > line && arr[high - 1][0] <= line) {
+ return high - 1;
+ }
+
+ target =
+ (((line - arr[low][0]) / (arr[high][0] - arr[low][0])) * (high - low)) |
+ 0;
+
+ if (arr[target][0] <= line && arr[target + 1][0] > line) {
+ return target;
+ } else if (line > arr[target][0]) {
+ low = target + 1;
+ high--;
+ } else {
+ high = target - 1;
+ low++;
+ }
+ }
+
+ return -1;
+ },
+
+ /**
+ * Invalidates the state cache for and above the line.
+ */
+ invalidateCache(line) {
+ this.nullStates.length = this.findNearestNullState(line) + 1;
+ },
+
+ /**
+ * Get the state information about a token surrounding the {line, ch} position
+ *
+ * @param {string} source
+ * The complete source of the CSS file. Unlike resolve state method,
+ * this method requires the full source.
+ * @param {object} caret
+ * The line, ch position of the caret.
+ *
+ * @returns {object}
+ * An object containing the state of token covered by the caret.
+ * The object has following properties when the the state is
+ * "selector", "value" or "property", null otherwise:
+ * - state {string} one of CSS_STATES - "selector", "value" etc.
+ * - selector {string} The selector at the caret when `state` is
+ * selector. OR
+ * - selectors {[string]} Array of selector strings in case when
+ * `state` is "value" or "property"
+ * - propertyName {string} The property name at the current caret or
+ * the property name corresponding to the value at
+ * the caret.
+ * - value {string} The css value at the current caret.
+ * - loc {object} An object containing the starting and the ending
+ * caret position of the whole selector, value or property.
+ * - { start: {line, ch}, end: {line, ch}}
+ */
+ getInfoAt(source, caret) {
+ // Limits the input source till the {line, ch} caret position
+ function limit(sourceArg, { line, ch }) {
+ line++;
+ const list = sourceArg.split("\n");
+ if (list.length < line) {
+ return sourceArg;
+ }
+ if (line == 1) {
+ return list[0].slice(0, ch);
+ }
+ return [...list.slice(0, line - 1), list[line - 1].slice(0, ch)].join(
+ "\n"
+ );
+ }
+
+ // Get the state at the given line, ch
+ const state = this.resolveState(limit(source, caret), caret);
+ const propertyName = this.propertyName;
+ let { line, ch } = caret;
+ const sourceArray = source.split("\n");
+ let limitedSource = limit(source, caret);
+
+ /**
+ * Method to traverse forwards from the caret location to figure out the
+ * ending point of a selector or css value.
+ *
+ * @param {function} check
+ * A method which takes the current state as an input and determines
+ * whether the state changed or not.
+ */
+ const traverseForward = check => {
+ let location;
+ // Backward loop to determine the beginning location of the selector.
+ do {
+ let lineText = sourceArray[line];
+ if (line == caret.line) {
+ lineText = lineText.substring(caret.ch);
+ }
+
+ let prevToken = undefined;
+ const tokens = cssTokenizer(lineText);
+ let found = false;
+ const ech = line == caret.line ? caret.ch : 0;
+ for (let token of tokens) {
+ // If the line is completely spaces, handle it differently
+ if (lineText.trim() == "") {
+ limitedSource += lineText;
+ } else {
+ limitedSource += sourceArray[line].substring(
+ ech + token.startOffset,
+ ech + token.endOffset
+ );
+ }
+
+ // Whitespace cannot change state.
+ if (token.tokenType == "whitespace") {
+ prevToken = token;
+ continue;
+ }
+
+ const forwState = this.resolveState(limitedSource, {
+ line,
+ ch: token.endOffset + ech,
+ });
+ if (check(forwState)) {
+ if (prevToken && prevToken.tokenType == "whitespace") {
+ token = prevToken;
+ }
+ location = {
+ line,
+ ch: token.startOffset + ech,
+ };
+ found = true;
+ break;
+ }
+ prevToken = token;
+ }
+ limitedSource += "\n";
+ if (found) {
+ break;
+ }
+ } while (line++ < sourceArray.length);
+ return location;
+ };
+
+ /**
+ * Method to traverse backwards from the caret location to figure out the
+ * starting point of a selector or css value.
+ *
+ * @param {function} check
+ * A method which takes the current state as an input and determines
+ * whether the state changed or not.
+ * @param {boolean} isValue
+ * true if the traversal is being done for a css value state.
+ */
+ const traverseBackwards = (check, isValue) => {
+ let location;
+ // Backward loop to determine the beginning location of the selector.
+ do {
+ let lineText = sourceArray[line];
+ if (line == caret.line) {
+ lineText = lineText.substring(0, caret.ch);
+ }
+
+ const tokens = Array.from(cssTokenizer(lineText));
+ let found = false;
+ for (let i = tokens.length - 1; i >= 0; i--) {
+ let token = tokens[i];
+ // If the line is completely spaces, handle it differently
+ if (lineText.trim() == "") {
+ limitedSource = limitedSource.slice(0, -1 * lineText.length);
+ } else {
+ const length = token.endOffset - token.startOffset;
+ limitedSource = limitedSource.slice(0, -1 * length);
+ }
+
+ // Whitespace cannot change state.
+ if (token.tokenType == "whitespace") {
+ continue;
+ }
+
+ const backState = this.resolveState(limitedSource, {
+ line,
+ ch: token.startOffset,
+ });
+ if (check(backState)) {
+ if (tokens[i + 1] && tokens[i + 1].tokenType == "whitespace") {
+ token = tokens[i + 1];
+ }
+ location = {
+ line,
+ ch: isValue ? token.endOffset : token.startOffset,
+ };
+ found = true;
+ break;
+ }
+ }
+ limitedSource = limitedSource.slice(0, -1);
+ if (found) {
+ break;
+ }
+ } while (line-- >= 0);
+ return location;
+ };
+
+ if (state == CSS_STATES.selector) {
+ // For selector state, the ending and starting point of the selector is
+ // either when the state changes or the selector becomes empty and a
+ // single selector can span multiple lines.
+ // Backward loop to determine the beginning location of the selector.
+ const start = traverseBackwards(backState => {
+ return (
+ backState != CSS_STATES.selector ||
+ (this.selector == "" && this.selectorBeforeNot == null)
+ );
+ });
+
+ line = caret.line;
+ limitedSource = limit(source, caret);
+ // Forward loop to determine the ending location of the selector.
+ const end = traverseForward(forwState => {
+ return (
+ forwState != CSS_STATES.selector ||
+ (this.selector == "" && this.selectorBeforeNot == null)
+ );
+ });
+
+ // Since we have start and end positions, figure out the whole selector.
+ let selector = source.split("\n").slice(start.line, end.line + 1);
+ selector[selector.length - 1] = selector[selector.length - 1].substring(
+ 0,
+ end.ch
+ );
+ selector[0] = selector[0].substring(start.ch);
+ selector = selector.join("\n");
+ return {
+ state,
+ selector,
+ loc: {
+ start,
+ end,
+ },
+ };
+ } else if (state == CSS_STATES.property) {
+ // A property can only be a single word and thus very easy to calculate.
+ const tokens = cssTokenizer(sourceArray[line]);
+ for (const token of tokens) {
+ // Note that, because we're tokenizing a single line, the
+ // token's offset is also the column number.
+ if (token.startOffset <= ch && token.endOffset >= ch) {
+ return {
+ state,
+ propertyName: token.text,
+ selectors: this.selectors,
+ loc: {
+ start: {
+ line,
+ ch: token.startOffset,
+ },
+ end: {
+ line,
+ ch: token.endOffset,
+ },
+ },
+ };
+ }
+ }
+ } else if (state == CSS_STATES.value) {
+ // CSS value can be multiline too, so we go forward and backwards to
+ // determine the bounds of the value at caret
+ const start = traverseBackwards(
+ backState => backState != CSS_STATES.value,
+ true
+ );
+
+ line = caret.line;
+ limitedSource = limit(source, caret);
+ const end = traverseForward(forwState => forwState != CSS_STATES.value);
+
+ let value = source.split("\n").slice(start.line, end.line + 1);
+ value[value.length - 1] = value[value.length - 1].substring(0, end.ch);
+ value[0] = value[0].substring(start.ch);
+ value = value.join("\n");
+ return {
+ state,
+ propertyName,
+ selectors: this.selectors,
+ value,
+ loc: {
+ start,
+ end,
+ },
+ };
+ }
+ return null;
+ },
+};
+
+module.exports = CSSCompleter;
diff --git a/devtools/client/shared/sourceeditor/editor-commands-controller.js b/devtools/client/shared/sourceeditor/editor-commands-controller.js
new file mode 100644
index 0000000000..25efad0850
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/editor-commands-controller.js
@@ -0,0 +1,97 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+/**
+ * The source editor exposes XUL commands that can be used when embedded in a XUL
+ * document. This controller drives the availability and behavior of the commands. When
+ * the editor input field is focused, this controller will update the matching menu item
+ * entries found in application menus or context menus.
+ */
+
+/**
+ * Returns a controller object that can be used for editor-specific commands:
+ * - find
+ * - find again
+ * - go to line
+ * - undo
+ * - redo
+ * - delete
+ * - select all
+ */
+function createController(ed) {
+ return {
+ supportsCommand(cmd) {
+ switch (cmd) {
+ case "cmd_find":
+ case "cmd_findAgain":
+ case "cmd_gotoLine":
+ case "cmd_undo":
+ case "cmd_redo":
+ case "cmd_delete":
+ case "cmd_selectAll":
+ return true;
+ }
+
+ return false;
+ },
+
+ isCommandEnabled(cmd) {
+ const cm = ed.codeMirror;
+
+ switch (cmd) {
+ case "cmd_find":
+ case "cmd_gotoLine":
+ case "cmd_selectAll":
+ return true;
+ case "cmd_findAgain":
+ return cm.state.search != null && cm.state.search.query != null;
+ case "cmd_undo":
+ return ed.canUndo();
+ case "cmd_redo":
+ return ed.canRedo();
+ case "cmd_delete":
+ return ed.somethingSelected();
+ }
+
+ return false;
+ },
+
+ doCommand(cmd) {
+ const cm = ed.codeMirror;
+
+ const map = {
+ cmd_selectAll: "selectAll",
+ cmd_find: "find",
+ cmd_undo: "undo",
+ cmd_redo: "redo",
+ cmd_delete: "delCharAfter",
+ cmd_findAgain: "findNext",
+ };
+
+ if (map[cmd]) {
+ cm.execCommand(map[cmd]);
+ return;
+ }
+
+ if (cmd == "cmd_gotoLine") {
+ ed.jumpToLine();
+ }
+ },
+
+ onEvent() {},
+ };
+}
+
+/**
+ * Create and insert a commands controller for the provided SourceEditor instance.
+ */
+function insertCommandsController(sourceEditor) {
+ const input = sourceEditor.codeMirror.getInputField();
+ const controller = createController(sourceEditor);
+ input.controllers.insertControllerAt(0, controller);
+}
+
+module.exports = { insertCommandsController };
diff --git a/devtools/client/shared/sourceeditor/editor.js b/devtools/client/shared/sourceeditor/editor.js
new file mode 100644
index 0000000000..c379a6b411
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/editor.js
@@ -0,0 +1,1818 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+const {
+ EXPAND_TAB,
+ TAB_SIZE,
+ DETECT_INDENT,
+ getIndentationFromIteration,
+} = require("resource://devtools/shared/indentation.js");
+
+const ENABLE_CODE_FOLDING = "devtools.editor.enableCodeFolding";
+const KEYMAP_PREF = "devtools.editor.keymap";
+const AUTO_CLOSE = "devtools.editor.autoclosebrackets";
+const AUTOCOMPLETE = "devtools.editor.autocomplete";
+const CARET_BLINK_TIME = "ui.caretBlinkTime";
+const XHTML_NS = "http://www.w3.org/1999/xhtml";
+
+const VALID_KEYMAPS = new Map([
+ [
+ "emacs",
+ "chrome://devtools/content/shared/sourceeditor/codemirror/keymap/emacs.js",
+ ],
+ [
+ "vim",
+ "chrome://devtools/content/shared/sourceeditor/codemirror/keymap/vim.js",
+ ],
+ [
+ "sublime",
+ "chrome://devtools/content/shared/sourceeditor/codemirror/keymap/sublime.js",
+ ],
+]);
+
+// Maximum allowed margin (in number of lines) from top or bottom of the editor
+// while shifting to a line which was initially out of view.
+const MAX_VERTICAL_OFFSET = 3;
+
+const RE_JUMP_TO_LINE = /^(\d+):?(\d+)?/;
+const AUTOCOMPLETE_MARK_CLASSNAME = "cm-auto-complete-shadow-text";
+
+const EventEmitter = require("resource://devtools/shared/event-emitter.js");
+const { PrefObserver } = require("resource://devtools/client/shared/prefs.js");
+const KeyShortcuts = require("resource://devtools/client/shared/key-shortcuts.js");
+
+const { LocalizationHelper } = require("resource://devtools/shared/l10n.js");
+const L10N = new LocalizationHelper(
+ "devtools/client/locales/sourceeditor.properties"
+);
+
+loader.lazyRequireGetter(
+ this,
+ "wasm",
+ "resource://devtools/client/shared/sourceeditor/wasm.js"
+);
+
+const { OS } = Services.appinfo;
+
+// CM_BUNDLE and CM_IFRAME represent the HTML and JavaScript that is
+// injected into an iframe in order to initialize a CodeMirror instance.
+
+const CM_BUNDLE =
+ "chrome://devtools/content/shared/sourceeditor/codemirror/codemirror.bundle.js";
+const CM6_BUNDLE =
+ "resource://devtools/client/shared/sourceeditor/codemirror6/codemirror6.bundle.js";
+
+const CM_IFRAME =
+ "chrome://devtools/content/shared/sourceeditor/codemirror/cmiframe.html";
+
+const CM_MAPPING = [
+ "clearHistory",
+ "defaultCharWidth",
+ "extendSelection",
+ "focus",
+ "getCursor",
+ "getLine",
+ "getScrollInfo",
+ "getSelection",
+ "getViewport",
+ "hasFocus",
+ "lineCount",
+ "openDialog",
+ "redo",
+ "refresh",
+ "replaceSelection",
+ "setSelection",
+ "somethingSelected",
+ "undo",
+];
+
+const editors = new WeakMap();
+
+/**
+ * A very thin wrapper around CodeMirror. Provides a number
+ * of helper methods to make our use of CodeMirror easier and
+ * another method, appendTo, to actually create and append
+ * the CodeMirror instance.
+ *
+ * Note that Editor doesn't expose CodeMirror instance to the
+ * outside world.
+ *
+ * Constructor accepts one argument, config. It is very
+ * similar to the CodeMirror configuration object so for most
+ * properties go to CodeMirror's documentation (see below).
+ *
+ * Other than that, it accepts one additional and optional
+ * property contextMenu. This property should be an element, or
+ * an ID of an element that we can use as a context menu.
+ *
+ * This object is also an event emitter.
+ *
+ * CodeMirror docs: http://codemirror.net/doc/manual.html
+ */
+class Editor extends EventEmitter {
+ // Static methods on the Editor object itself.
+
+ /**
+ * Returns a string representation of a shortcut 'key' with
+ * a OS specific modifier. Cmd- for Macs, Ctrl- for other
+ * platforms. Useful with extraKeys configuration option.
+ *
+ * CodeMirror defines all keys with modifiers in the following
+ * order: Shift - Ctrl/Cmd - Alt - Key
+ */
+ static accel(key, modifiers = {}) {
+ return (
+ (modifiers.shift ? "Shift-" : "") +
+ (Services.appinfo.OS == "Darwin" ? "Cmd-" : "Ctrl-") +
+ (modifiers.alt ? "Alt-" : "") +
+ key
+ );
+ }
+
+ /**
+ * Returns a string representation of a shortcut for a
+ * specified command 'cmd'. Append Cmd- for macs, Ctrl- for other
+ * platforms unless noaccel is specified in the options. Useful when overwriting
+ * or disabling default shortcuts.
+ */
+ static keyFor(cmd, opts = { noaccel: false }) {
+ const key = L10N.getStr(cmd + ".commandkey");
+ return opts.noaccel ? key : Editor.accel(key);
+ }
+
+ static modes = {
+ cljs: { name: "text/x-clojure" },
+ css: { name: "css" },
+ fs: { name: "x-shader/x-fragment" },
+ haxe: { name: "haxe" },
+ http: { name: "http" },
+ html: { name: "htmlmixed" },
+ js: { name: "javascript" },
+ text: { name: "text" },
+ vs: { name: "x-shader/x-vertex" },
+ wasm: { name: "wasm" },
+ };
+
+ container = null;
+ version = null;
+ config = null;
+ Doc = null;
+
+ #compartments;
+ #lastDirty;
+ #loadedKeyMaps;
+ #ownerDoc;
+ #prefObserver;
+
+ constructor(config) {
+ super();
+
+ const tabSize = Services.prefs.getIntPref(TAB_SIZE);
+ const useTabs = !Services.prefs.getBoolPref(EXPAND_TAB);
+ const useAutoClose = Services.prefs.getBoolPref(AUTO_CLOSE);
+
+ this.version = null;
+ this.config = {
+ cm6: false,
+ value: "",
+ mode: Editor.modes.text,
+ indentUnit: tabSize,
+ tabSize,
+ contextMenu: null,
+ matchBrackets: true,
+ highlightSelectionMatches: {
+ wordsOnly: true,
+ },
+ extraKeys: {},
+ indentWithTabs: useTabs,
+ inputStyle: "accessibleTextArea",
+ // This is set to the biggest value for setTimeout (See https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Maximum_delay_value)
+ // This is because codeMirror queries the underlying textArea for some things that
+ // can't be retrieved with events in some browser (but we're fine in Firefox).
+ pollInterval: Math.pow(2, 31) - 1,
+ styleActiveLine: true,
+ autoCloseBrackets: "()[]{}''\"\"``",
+ autoCloseEnabled: useAutoClose,
+ theme: "mozilla",
+ themeSwitching: true,
+ autocomplete: false,
+ autocompleteOpts: {},
+ // Expect a CssProperties object (see devtools/client/fronts/css-properties.js)
+ cssProperties: null,
+ // Set to true to prevent the search addon to be activated.
+ disableSearchAddon: false,
+ maxHighlightLength: 1000,
+ // Disable codeMirror setTimeout-based cursor blinking (will be replaced by a CSS animation)
+ cursorBlinkRate: 0,
+ // List of non-printable chars that will be displayed in the editor, showing their
+ // unicode version. We only add a few characters to the default list:
+ // - \u202d LEFT-TO-RIGHT OVERRIDE
+ // - \u202e RIGHT-TO-LEFT OVERRIDE
+ // - \u2066 LEFT-TO-RIGHT ISOLATE
+ // - \u2067 RIGHT-TO-LEFT ISOLATE
+ // - \u2069 POP DIRECTIONAL ISOLATE
+ specialChars:
+ // eslint-disable-next-line no-control-regex
+ /[\u0000-\u001f\u007f-\u009f\u00ad\u061c\u200b-\u200f\u2028\u2029\u202d\u202e\u2066\u2067\u2069\ufeff\ufff9-\ufffc]/,
+ specialCharPlaceholder: char => {
+ // Use the doc provided to the setup function if we don't have a reference to a codeMirror
+ // editor yet (this can happen when an Editor is being created with existing content)
+ const doc = this.#ownerDoc;
+ const el = doc.createElement("span");
+ el.classList.add("cm-non-printable-char");
+ el.append(doc.createTextNode(`\\u${char.codePointAt(0).toString(16)}`));
+ return el;
+ },
+ };
+
+ // Additional shortcuts.
+ this.config.extraKeys[Editor.keyFor("jumpToLine")] = () =>
+ this.jumpToLine();
+ this.config.extraKeys[Editor.keyFor("moveLineUp", { noaccel: true })] =
+ () => this.moveLineUp();
+ this.config.extraKeys[Editor.keyFor("moveLineDown", { noaccel: true })] =
+ () => this.moveLineDown();
+ this.config.extraKeys[Editor.keyFor("toggleComment")] = "toggleComment";
+
+ // Disable ctrl-[ and ctrl-] because toolbox uses those shortcuts.
+ this.config.extraKeys[Editor.keyFor("indentLess")] = false;
+ this.config.extraKeys[Editor.keyFor("indentMore")] = false;
+
+ // Disable Alt-B and Alt-F to navigate groups (respectively previous and next) since:
+ // - it's not standard in input fields
+ // - it also inserts a character which feels weird
+ this.config.extraKeys["Alt-B"] = false;
+ this.config.extraKeys["Alt-F"] = false;
+
+ // Disable Ctrl/Cmd + U as it's used for "View Source". It's okay to disable Ctrl+U as
+ // the underlying command, `undoSelection`, isn't standard in input fields and isn't
+ // widely known.
+ this.config.extraKeys[Editor.accel("U")] = false;
+
+ // Disable keys that trigger events with a null-string `which` property.
+ // It looks like some of those (e.g. the Function key), can trigger a poll
+ // which fails to see that there's a selection, which end up replacing the
+ // selected text with an empty string.
+ // TODO: We should investigate the root cause.
+ this.config.extraKeys["'\u0000'"] = false;
+
+ // Overwrite default config with user-provided, if needed.
+ Object.keys(config).forEach(k => {
+ if (k != "extraKeys") {
+ this.config[k] = config[k];
+ return;
+ }
+
+ if (!config.extraKeys) {
+ return;
+ }
+
+ Object.keys(config.extraKeys).forEach(key => {
+ this.config.extraKeys[key] = config.extraKeys[key];
+ });
+ });
+
+ if (!this.config.gutters) {
+ this.config.gutters = [];
+ }
+ if (
+ this.config.lineNumbers &&
+ !this.config.gutters.includes("CodeMirror-linenumbers")
+ ) {
+ this.config.gutters.push("CodeMirror-linenumbers");
+ }
+
+ // Remember the initial value of autoCloseBrackets.
+ this.config.autoCloseBracketsSaved = this.config.autoCloseBrackets;
+
+ // Overwrite default tab behavior. If something is selected,
+ // indent those lines. If nothing is selected and we're
+ // indenting with tabs, insert one tab. Otherwise insert N
+ // whitespaces where N == indentUnit option.
+ this.config.extraKeys.Tab = cm => {
+ if (config.extraKeys?.Tab) {
+ // If a consumer registers its own extraKeys.Tab, we execute it before doing
+ // anything else. If it returns false, that mean that all the key handling work is
+ // done, so we can do an early return.
+ const res = config.extraKeys.Tab(cm);
+ if (res === false) {
+ return;
+ }
+ }
+
+ if (cm.somethingSelected()) {
+ cm.indentSelection("add");
+ return;
+ }
+
+ if (this.config.indentWithTabs) {
+ cm.replaceSelection("\t", "end", "+input");
+ return;
+ }
+
+ let num = cm.getOption("indentUnit");
+ if (cm.getCursor().ch !== 0) {
+ num -= cm.getCursor().ch % num;
+ }
+ cm.replaceSelection(" ".repeat(num), "end", "+input");
+ };
+
+ if (this.config.cssProperties) {
+ // Ensure that autocompletion has cssProperties if it's passed in via the options.
+ this.config.autocompleteOpts.cssProperties = this.config.cssProperties;
+ }
+ }
+
+ /**
+ * Exposes the CodeMirror class. We want to be able to
+ * invoke static commands such as runMode for syntax highlighting.
+ */
+ get CodeMirror() {
+ const codeMirror = editors.get(this);
+ return codeMirror?.constructor;
+ }
+
+ /**
+ * Exposes the CodeMirror instance. We want to get away from trying to
+ * abstract away the API entirely, and this makes it easier to integrate in
+ * various environments and do complex things.
+ */
+ get codeMirror() {
+ if (!editors.has(this)) {
+ throw new Error(
+ "CodeMirror instance does not exist. You must wait " +
+ "for it to be appended to the DOM."
+ );
+ }
+ return editors.get(this);
+ }
+
+ /**
+ * Return whether there is a CodeMirror instance associated with this Editor.
+ */
+ get hasCodeMirror() {
+ return editors.has(this);
+ }
+
+ /**
+ * Appends the current Editor instance to the element specified by
+ * 'el'. You can also provide your own iframe to host the editor as
+ * an optional second parameter. This method actually creates and
+ * loads CodeMirror and all its dependencies.
+ *
+ * This method is asynchronous and returns a promise.
+ */
+ appendTo(el, env) {
+ return new Promise(resolve => {
+ const cm = editors.get(this);
+
+ if (!env) {
+ env = el.ownerDocument.createElementNS(XHTML_NS, "iframe");
+ env.className = "source-editor-frame";
+ }
+
+ if (cm) {
+ throw new Error("You can append an editor only once.");
+ }
+
+ const onLoad = () => {
+ // Prevent flickering by showing the iframe once loaded.
+ // See https://github.com/w3c/csswg-drafts/issues/9624
+ env.style.visibility = "";
+ const win = env.contentWindow.wrappedJSObject;
+ this.container = env;
+
+ const editorEl = win.document.body;
+ const editorDoc = el.ownerDocument;
+ if (this.config.cm6) {
+ this.#setupCm6(editorEl, editorDoc);
+ } else {
+ this.#setup(editorEl, editorDoc);
+ }
+ resolve();
+ };
+
+ env.style.visibility = "hidden";
+ env.addEventListener("load", onLoad, { capture: true, once: true });
+ env.src = CM_IFRAME;
+ el.appendChild(env);
+
+ this.once("destroy", () => el.removeChild(env));
+ });
+ }
+
+ appendToLocalElement(el) {
+ if (this.config.cm6) {
+ this.#setupCm6(el);
+ } else {
+ this.#setup(el);
+ }
+ }
+
+ /**
+ * Do the actual appending and configuring of the CodeMirror instance. This is
+ * used by both append functions above, and does all the hard work to
+ * configure CodeMirror with all the right options/modes/etc.
+ */
+ #setup(el, doc) {
+ this.#ownerDoc = doc || el.ownerDocument;
+ const win = el.ownerDocument.defaultView;
+
+ Services.scriptloader.loadSubScript(CM_BUNDLE, win);
+
+ if (this.config.cssProperties) {
+ // Replace the propertyKeywords, colorKeywords and valueKeywords
+ // properties of the CSS MIME type with the values provided by the CSS properties
+ // database.
+ const { propertyKeywords, colorKeywords, valueKeywords } = getCSSKeywords(
+ this.config.cssProperties
+ );
+
+ const cssSpec = win.CodeMirror.resolveMode("text/css");
+ cssSpec.propertyKeywords = propertyKeywords;
+ cssSpec.colorKeywords = colorKeywords;
+ cssSpec.valueKeywords = valueKeywords;
+ win.CodeMirror.defineMIME("text/css", cssSpec);
+
+ const scssSpec = win.CodeMirror.resolveMode("text/x-scss");
+ scssSpec.propertyKeywords = propertyKeywords;
+ scssSpec.colorKeywords = colorKeywords;
+ scssSpec.valueKeywords = valueKeywords;
+ win.CodeMirror.defineMIME("text/x-scss", scssSpec);
+ }
+
+ win.CodeMirror.commands.save = () => this.emit("saveRequested");
+
+ // Create a CodeMirror instance add support for context menus,
+ // overwrite the default controller (otherwise items in the top and
+ // context menus won't work).
+
+ const cm = win.CodeMirror(el, this.config);
+ this.Doc = win.CodeMirror.Doc;
+
+ // Disable APZ for source editors. It currently causes the line numbers to
+ // "tear off" and swim around on top of the content. Bug 1160601 tracks
+ // finding a solution that allows APZ to work with CodeMirror.
+ cm.getScrollerElement().addEventListener("wheel", ev => {
+ // By handling the wheel events ourselves, we force the platform to
+ // scroll synchronously, like it did before APZ. However, we lose smooth
+ // scrolling for users with mouse wheels. This seems acceptible vs.
+ // doing nothing and letting the gutter slide around.
+ ev.preventDefault();
+
+ let { deltaX, deltaY } = ev;
+
+ if (ev.deltaMode == ev.DOM_DELTA_LINE) {
+ deltaX *= cm.defaultCharWidth();
+ deltaY *= cm.defaultTextHeight();
+ } else if (ev.deltaMode == ev.DOM_DELTA_PAGE) {
+ deltaX *= cm.getWrapperElement().clientWidth;
+ deltaY *= cm.getWrapperElement().clientHeight;
+ }
+
+ cm.getScrollerElement().scrollBy(deltaX, deltaY);
+ });
+
+ cm.getWrapperElement().addEventListener("contextmenu", ev => {
+ if (!this.config.contextMenu) {
+ return;
+ }
+
+ ev.stopPropagation();
+ ev.preventDefault();
+
+ let popup = this.config.contextMenu;
+ if (typeof popup == "string") {
+ popup = this.#ownerDoc.getElementById(this.config.contextMenu);
+ }
+
+ this.emit("popupOpen", ev, popup);
+ popup.openPopupAtScreen(ev.screenX, ev.screenY, true);
+ });
+
+ const pipedEvents = [
+ "beforeChange",
+ "blur",
+ "changes",
+ "cursorActivity",
+ "focus",
+ "keyHandled",
+ "scroll",
+ ];
+ for (const eventName of pipedEvents) {
+ cm.on(eventName, (...args) => this.emit(eventName, ...args));
+ }
+
+ cm.on("change", () => {
+ this.emit("change");
+ if (!this.#lastDirty) {
+ this.#lastDirty = true;
+ this.emit("dirty-change");
+ }
+ });
+
+ cm.on("gutterClick", (cmArg, line, gutter, ev) => {
+ const lineOrOffset = !this.isWasm ? line : this.lineToWasmOffset(line);
+ this.emit("gutterClick", lineOrOffset, ev.button);
+ });
+
+ win.CodeMirror.defineExtension("l10n", name => {
+ return L10N.getStr(name);
+ });
+
+ if (!this.config.disableSearchAddon) {
+ this.#initSearchShortcuts(win);
+ } else {
+ // Hotfix for Bug 1527898. We should remove those overrides as part of Bug 1527903.
+ Object.assign(win.CodeMirror.commands, {
+ find: null,
+ findPersistent: null,
+ findPersistentNext: null,
+ findPersistentPrev: null,
+ findNext: null,
+ findPrev: null,
+ clearSearch: null,
+ replace: null,
+ replaceAll: null,
+ });
+ }
+
+ // Retrieve the cursor blink rate from user preference, or fall back to CodeMirror's
+ // default value.
+ let cursorBlinkingRate = win.CodeMirror.defaults.cursorBlinkRate;
+ if (Services.prefs.prefHasUserValue(CARET_BLINK_TIME)) {
+ cursorBlinkingRate = Services.prefs.getIntPref(
+ CARET_BLINK_TIME,
+ cursorBlinkingRate
+ );
+ }
+ // This will be used in the animation-duration property we set on the cursor to
+ // implement the blinking animation. If cursorBlinkingRate is 0 or less, the cursor
+ // won't blink.
+ cm.getWrapperElement().style.setProperty(
+ "--caret-blink-time",
+ `${Math.max(0, cursorBlinkingRate)}ms`
+ );
+
+ editors.set(this, cm);
+
+ this.reloadPreferences = this.reloadPreferences.bind(this);
+ this.setKeyMap = this.setKeyMap.bind(this, win);
+
+ this.#prefObserver = new PrefObserver("devtools.editor.");
+ this.#prefObserver.on(TAB_SIZE, this.reloadPreferences);
+ this.#prefObserver.on(EXPAND_TAB, this.reloadPreferences);
+ this.#prefObserver.on(AUTO_CLOSE, this.reloadPreferences);
+ this.#prefObserver.on(AUTOCOMPLETE, this.reloadPreferences);
+ this.#prefObserver.on(DETECT_INDENT, this.reloadPreferences);
+ this.#prefObserver.on(ENABLE_CODE_FOLDING, this.reloadPreferences);
+
+ this.reloadPreferences();
+
+ // Init a map of the loaded keymap files. Should be of the form Map<String->Boolean>.
+ this.#loadedKeyMaps = new Set();
+ this.#prefObserver.on(KEYMAP_PREF, this.setKeyMap);
+ this.setKeyMap();
+
+ win.editor = this;
+ const editorReadyEvent = new win.CustomEvent("editorReady");
+ win.dispatchEvent(editorReadyEvent);
+ }
+
+ /**
+ * Do the actual appending and configuring of the CodeMirror 6 instance.
+ * This is used by appendTo and appendToLocalElement, and does all the hard work to
+ * configure CodeMirror 6 with all the right options/modes/etc.
+ * This should be kept in sync with #setup.
+ *
+ * @param {Element} el: Element into which the codeMirror editor should be appended.
+ * @param {Document} document: Optional document, if not set, will default to el.ownerDocument
+ */
+ #setupCm6(el, doc) {
+ this.#ownerDoc = doc || el.ownerDocument;
+ const win = el.ownerDocument.defaultView;
+
+ Services.scriptloader.loadSubScript(CM6_BUNDLE, win);
+
+ const {
+ codemirror,
+ codemirrorView: { EditorView, lineNumbers },
+ codemirrorState: { EditorState, Compartment },
+ codemirrorLanguage,
+ codemirrorLangJavascript,
+ lezerHighlight,
+ } = win.CodeMirror;
+
+ const tabSizeCompartment = new Compartment();
+ const indentCompartment = new Compartment();
+ this.#compartments = {
+ tabSizeCompartment,
+ indentCompartment,
+ };
+
+ const indentStr = (this.config.indentWithTabs ? "\t" : " ").repeat(
+ this.config.indentUnit || 2
+ );
+
+ const extensions = [
+ indentCompartment.of(codemirrorLanguage.indentUnit.of(indentStr)),
+ tabSizeCompartment.of(EditorState.tabSize.of(this.config.tabSize)),
+ EditorState.readOnly.of(this.config.readOnly),
+ codemirrorLanguage.codeFolding({
+ placeholderText: "↔",
+ }),
+ codemirrorLanguage.foldGutter({
+ class: "cm6-dt-foldgutter",
+ markerDOM: open => {
+ const button = doc.createElement("button");
+ button.classList.add("cm6-dt-foldgutter__toggle-button");
+ button.setAttribute("aria-expanded", open);
+ return button;
+ },
+ }),
+ codemirrorLanguage.syntaxHighlighting(lezerHighlight.classHighlighter),
+ // keep last so other extension take precedence
+ codemirror.minimalSetup,
+ ];
+
+ if (this.config.mode === Editor.modes.js) {
+ extensions.push(codemirrorLangJavascript.javascript());
+ }
+
+ if (this.config.lineNumbers) {
+ extensions.push(lineNumbers());
+ }
+
+ if (this.config.lineWrapping) {
+ extensions.push(EditorView.lineWrapping);
+ }
+
+ const cm = new EditorView({
+ parent: el,
+ extensions,
+ });
+
+ editors.set(this, cm);
+ }
+
+ /**
+ * Returns a boolean indicating whether the editor is ready to
+ * use. Use appendTo(el).then(() => {}) for most cases
+ */
+ isAppended() {
+ return editors.has(this);
+ }
+
+ /**
+ * Returns the currently active highlighting mode.
+ * See Editor.modes for the list of all suppoert modes.
+ */
+ getMode() {
+ return this.getOption("mode");
+ }
+
+ /**
+ * Loads a script into editor's containing window.
+ */
+ loadScript(url) {
+ if (!this.container) {
+ throw new Error("Can't load a script until the editor is loaded.");
+ }
+ const win = this.container.contentWindow.wrappedJSObject;
+ Services.scriptloader.loadSubScript(url, win);
+ }
+
+ /**
+ * Returns the container content window
+ * @returns {Window}
+ */
+ getContainerWindow() {
+ return this.container.contentWindow.wrappedJSObject;
+ }
+
+ /**
+ * Creates a CodeMirror Document
+ *
+ * @param {String} text: Initial text of the document
+ * @param {Object|String} mode: Mode of the document. See https://codemirror.net/5/doc/manual.html#option_mode
+ * @returns CodeMirror.Doc
+ */
+ createDocument(text = "", mode) {
+ return new this.Doc(text, mode);
+ }
+
+ /**
+ * Replaces the current document with a new source document
+ */
+ replaceDocument(doc) {
+ const cm = editors.get(this);
+ cm.swapDoc(doc);
+ }
+
+ /**
+ * Changes the value of a currently used highlighting mode.
+ * See Editor.modes for the list of all supported modes.
+ */
+ setMode(value) {
+ this.setOption("mode", value);
+
+ // If autocomplete was set up and the mode is changing, then
+ // turn it off and back on again so the proper mode can be used.
+ if (this.config.autocomplete) {
+ this.setOption("autocomplete", false);
+ this.setOption("autocomplete", true);
+ }
+ }
+
+ /**
+ * The source editor can expose several commands linked from system and context menus.
+ * Kept for backward compatibility with styleeditor.
+ */
+ insertCommandsController() {
+ const {
+ insertCommandsController,
+ } = require("resource://devtools/client/shared/sourceeditor/editor-commands-controller.js");
+ insertCommandsController(this);
+ }
+
+ /**
+ * Returns text from the text area. If line argument is provided
+ * the method returns only that line.
+ */
+ getText(line) {
+ const cm = editors.get(this);
+
+ if (line == null) {
+ return this.config.cm6 ? cm.state.doc.toString() : cm.getValue();
+ }
+
+ const info = this.lineInfo(line);
+ return info ? info.text : "";
+ }
+
+ getDoc() {
+ const cm = editors.get(this);
+ return cm.getDoc();
+ }
+
+ get isWasm() {
+ return wasm.isWasm(this.getDoc());
+ }
+
+ wasmOffsetToLine(offset) {
+ return wasm.wasmOffsetToLine(this.getDoc(), offset);
+ }
+
+ lineToWasmOffset(number) {
+ return wasm.lineToWasmOffset(this.getDoc(), number);
+ }
+
+ toLineIfWasmOffset(maybeOffset) {
+ if (typeof maybeOffset !== "number" || !this.isWasm) {
+ return maybeOffset;
+ }
+ return this.wasmOffsetToLine(maybeOffset);
+ }
+
+ lineInfo(lineOrOffset) {
+ const line = this.toLineIfWasmOffset(lineOrOffset);
+ if (line == undefined) {
+ return null;
+ }
+ const cm = editors.get(this);
+
+ if (this.config.cm6) {
+ return {
+ // cm6 lines are 1-based, while cm5 are 0-based
+ text: cm.state.doc.lineAt(line + 1)?.text,
+ // TODO: Expose those, or see usage for those and do things differently
+ line: null,
+ handle: null,
+ gutterMarkers: null,
+ textClass: null,
+ bgClass: null,
+ wrapClass: null,
+ widgets: null,
+ };
+ }
+
+ return cm.lineInfo(line);
+ }
+
+ getLineOrOffset(line) {
+ return this.isWasm ? this.lineToWasmOffset(line) : line;
+ }
+
+ /**
+ * Replaces whatever is in the text area with the contents of
+ * the 'value' argument.
+ */
+ setText(value) {
+ const cm = editors.get(this);
+
+ if (typeof value !== "string" && "binary" in value) {
+ // wasm?
+ // binary does not survive as Uint8Array, converting from string
+ const binary = value.binary;
+ const data = new Uint8Array(binary.length);
+ for (let i = 0; i < data.length; i++) {
+ data[i] = binary.charCodeAt(i);
+ }
+ const { lines, done } = wasm.getWasmText(this.getDoc(), data);
+ const MAX_LINES = 10000000;
+ if (lines.length > MAX_LINES) {
+ lines.splice(MAX_LINES, lines.length - MAX_LINES);
+ lines.push(";; .... text is truncated due to the size");
+ }
+ if (!done) {
+ lines.push(";; .... possible error during wast conversion");
+ }
+ // cm will try to split into lines anyway, saving memory
+ value = { split: () => lines };
+ }
+
+ if (this.config.cm6) {
+ cm.dispatch({
+ changes: { from: 0, to: cm.state.doc.length, insert: value },
+ });
+ } else {
+ cm.setValue(value);
+ }
+
+ this.resetIndentUnit();
+ }
+
+ /**
+ * Reloads the state of the editor based on all current preferences.
+ * This is called automatically when any of the relevant preferences
+ * change.
+ */
+ reloadPreferences() {
+ // Restore the saved autoCloseBrackets value if it is preffed on.
+ const useAutoClose = Services.prefs.getBoolPref(AUTO_CLOSE);
+ this.setOption(
+ "autoCloseBrackets",
+ useAutoClose ? this.config.autoCloseBracketsSaved : false
+ );
+
+ this.updateCodeFoldingGutter();
+
+ this.resetIndentUnit();
+ this.setupAutoCompletion();
+ }
+
+ /**
+ * Set the current keyMap for CodeMirror, and load the support file if needed.
+ *
+ * @param {Window} win: The window on which the keymap files should be loaded.
+ */
+ setKeyMap(win) {
+ if (this.config.isReadOnly) {
+ return;
+ }
+
+ const keyMap = Services.prefs.getCharPref(KEYMAP_PREF);
+
+ // If alternative keymap is provided, use it.
+ if (VALID_KEYMAPS.has(keyMap)) {
+ if (!this.#loadedKeyMaps.has(keyMap)) {
+ Services.scriptloader.loadSubScript(VALID_KEYMAPS.get(keyMap), win);
+ this.#loadedKeyMaps.add(keyMap);
+ }
+ this.setOption("keyMap", keyMap);
+ } else {
+ this.setOption("keyMap", "default");
+ }
+ }
+
+ /**
+ * Sets the editor's indentation based on the current prefs and
+ * re-detect indentation if we should.
+ */
+ resetIndentUnit() {
+ const cm = editors.get(this);
+
+ const iterFn = (start, maxEnd, callback) => {
+ if (!this.config.cm6) {
+ cm.eachLine(start, maxEnd, line => {
+ return callback(line.text);
+ });
+ } else {
+ const iterator = cm.state.doc.iterLines(
+ start + 1,
+ Math.min(cm.state.doc.lines, maxEnd) + 1
+ );
+ let callbackRes;
+ do {
+ iterator.next();
+ callbackRes = callback(iterator.value);
+ } while (iterator.done !== true && !callbackRes);
+ }
+ };
+
+ const { indentUnit, indentWithTabs } = getIndentationFromIteration(iterFn);
+
+ if (!this.config.cm6) {
+ cm.setOption("tabSize", indentUnit);
+ cm.setOption("indentUnit", indentUnit);
+ cm.setOption("indentWithTabs", indentWithTabs);
+ } else {
+ const {
+ codemirrorState: { EditorState },
+ codemirrorLanguage,
+ } = this.getContainerWindow().CodeMirror;
+
+ cm.dispatch({
+ effects: this.#compartments.tabSizeCompartment.reconfigure(
+ EditorState.tabSize.of(indentUnit)
+ ),
+ });
+ cm.dispatch({
+ effects: this.#compartments.indentCompartment.reconfigure(
+ codemirrorLanguage.indentUnit.of(
+ (indentWithTabs ? "\t" : " ").repeat(indentUnit)
+ )
+ ),
+ });
+ }
+ }
+
+ /**
+ * Replaces contents of a text area within the from/to {line, ch}
+ * range. If neither `from` nor `to` arguments are provided works
+ * exactly like setText. If only `from` object is provided, inserts
+ * text at that point, *overwriting* as many characters as needed.
+ */
+ replaceText(value, from, to) {
+ const cm = editors.get(this);
+
+ if (!from) {
+ this.setText(value);
+ return;
+ }
+
+ if (!to) {
+ const text = cm.getRange({ line: 0, ch: 0 }, from);
+ this.setText(text + value);
+ return;
+ }
+
+ cm.replaceRange(value, from, to);
+ }
+
+ /**
+ * Inserts text at the specified {line, ch} position, shifting existing
+ * contents as necessary.
+ */
+ insertText(value, at) {
+ const cm = editors.get(this);
+ cm.replaceRange(value, at, at);
+ }
+
+ /**
+ * Deselects contents of the text area.
+ */
+ dropSelection() {
+ if (!this.somethingSelected()) {
+ return;
+ }
+
+ this.setCursor(this.getCursor());
+ }
+
+ /**
+ * Returns true if there is more than one selection in the editor.
+ */
+ hasMultipleSelections() {
+ const cm = editors.get(this);
+ return cm.listSelections().length > 1;
+ }
+
+ /**
+ * Gets the first visible line number in the editor.
+ */
+ getFirstVisibleLine() {
+ const cm = editors.get(this);
+ return cm.lineAtHeight(0, "local");
+ }
+
+ /**
+ * Scrolls the view such that the given line number is the first visible line.
+ */
+ setFirstVisibleLine(line) {
+ const cm = editors.get(this);
+ const { top } = cm.charCoords({ line, ch: 0 }, "local");
+ cm.scrollTo(0, top);
+ }
+
+ /**
+ * Sets the cursor to the specified {line, ch} position with an additional
+ * option to align the line at the "top", "center" or "bottom" of the editor
+ * with "top" being default value.
+ */
+ setCursor({ line, ch }, align) {
+ const cm = editors.get(this);
+ this.alignLine(line, align);
+ cm.setCursor({ line, ch });
+ this.emit("cursorActivity");
+ }
+
+ /**
+ * Aligns the provided line to either "top", "center" or "bottom" of the
+ * editor view with a maximum margin of MAX_VERTICAL_OFFSET lines from top or
+ * bottom.
+ */
+ alignLine(line, align) {
+ const cm = editors.get(this);
+ const from = cm.lineAtHeight(0, "page");
+ const to = cm.lineAtHeight(cm.getWrapperElement().clientHeight, "page");
+ const linesVisible = to - from;
+ const halfVisible = Math.round(linesVisible / 2);
+
+ // If the target line is in view, skip the vertical alignment part.
+ if (line <= to && line >= from) {
+ return;
+ }
+
+ // Setting the offset so that the line always falls in the upper half
+ // of visible lines (lower half for bottom aligned).
+ // MAX_VERTICAL_OFFSET is the maximum allowed value.
+ const offset = Math.min(halfVisible, MAX_VERTICAL_OFFSET);
+
+ let topLine =
+ {
+ center: Math.max(line - halfVisible, 0),
+ bottom: Math.max(line - linesVisible + offset, 0),
+ top: Math.max(line - offset, 0),
+ }[align || "top"] || offset;
+
+ // Bringing down the topLine to total lines in the editor if exceeding.
+ topLine = Math.min(topLine, this.lineCount());
+ this.setFirstVisibleLine(topLine);
+ }
+
+ /**
+ * Returns whether a marker of a specified class exists in a line's gutter.
+ */
+ hasMarker(line, gutterName, markerClass) {
+ const marker = this.getMarker(line, gutterName);
+ if (!marker) {
+ return false;
+ }
+
+ return marker.classList.contains(markerClass);
+ }
+
+ /**
+ * Adds a marker with a specified class to a line's gutter. If another marker
+ * exists on that line, the new marker class is added to its class list.
+ */
+ addMarker(line, gutterName, markerClass) {
+ const cm = editors.get(this);
+ const info = this.lineInfo(line);
+ if (!info) {
+ return;
+ }
+
+ const gutterMarkers = info.gutterMarkers;
+ let marker;
+ if (gutterMarkers) {
+ marker = gutterMarkers[gutterName];
+ if (marker) {
+ marker.classList.add(markerClass);
+ return;
+ }
+ }
+
+ marker = cm.getWrapperElement().ownerDocument.createElement("div");
+ marker.className = markerClass;
+ cm.setGutterMarker(info.line, gutterName, marker);
+ }
+
+ /**
+ * The reverse of addMarker. Removes a marker of a specified class from a
+ * line's gutter.
+ */
+ removeMarker(line, gutterName, markerClass) {
+ if (!this.hasMarker(line, gutterName, markerClass)) {
+ return;
+ }
+
+ this.lineInfo(line).gutterMarkers[gutterName].classList.remove(markerClass);
+ }
+
+ /**
+ * Adds a marker with a specified class and an HTML content to a line's
+ * gutter. If another marker exists on that line, it is overwritten by a new
+ * marker.
+ */
+ addContentMarker(line, gutterName, markerClass, content) {
+ const cm = editors.get(this);
+ const info = this.lineInfo(line);
+ if (!info) {
+ return;
+ }
+
+ const marker = cm.getWrapperElement().ownerDocument.createElement("div");
+ marker.className = markerClass;
+ // eslint-disable-next-line no-unsanitized/property
+ marker.innerHTML = content;
+ cm.setGutterMarker(info.line, gutterName, marker);
+ }
+
+ /**
+ * The reverse of addContentMarker. Removes any line's markers in the
+ * specified gutter.
+ */
+ removeContentMarker(line, gutterName) {
+ const cm = editors.get(this);
+ const info = this.lineInfo(line);
+ if (!info) {
+ return;
+ }
+
+ cm.setGutterMarker(info.line, gutterName, null);
+ }
+
+ getMarker(line, gutterName) {
+ const info = this.lineInfo(line);
+ if (!info) {
+ return null;
+ }
+
+ const gutterMarkers = info.gutterMarkers;
+ if (!gutterMarkers) {
+ return null;
+ }
+
+ return gutterMarkers[gutterName];
+ }
+
+ /**
+ * Removes all gutter markers in the gutter with the given name.
+ */
+ removeAllMarkers(gutterName) {
+ const cm = editors.get(this);
+ cm.clearGutter(gutterName);
+ }
+
+ /**
+ * Handles attaching a set of events listeners on a marker. They should
+ * be passed as an object literal with keys as event names and values as
+ * function listeners. The line number, marker node and optional data
+ * will be passed as arguments to the function listener.
+ *
+ * You don't need to worry about removing these event listeners.
+ * They're automatically orphaned when clearing markers.
+ */
+ setMarkerListeners(line, gutterName, markerClass, eventsArg, data) {
+ if (!this.hasMarker(line, gutterName, markerClass)) {
+ return;
+ }
+
+ const cm = editors.get(this);
+ const marker = cm.lineInfo(line).gutterMarkers[gutterName];
+
+ for (const name in eventsArg) {
+ const listener = eventsArg[name].bind(this, line, marker, data);
+ marker.addEventListener(name, listener);
+ }
+ }
+
+ /**
+ * Returns whether a line is decorated using the specified class name.
+ */
+ hasLineClass(line, className) {
+ const info = this.lineInfo(line);
+
+ if (!info || !info.wrapClass) {
+ return false;
+ }
+
+ return info.wrapClass.split(" ").includes(className);
+ }
+
+ /**
+ * Sets a CSS class name for the given line, including the text and gutter.
+ */
+ addLineClass(lineOrOffset, className) {
+ const cm = editors.get(this);
+ const line = this.toLineIfWasmOffset(lineOrOffset);
+ cm.addLineClass(line, "wrap", className);
+ }
+
+ /**
+ * The reverse of addLineClass.
+ */
+ removeLineClass(lineOrOffset, className) {
+ const cm = editors.get(this);
+ const line = this.toLineIfWasmOffset(lineOrOffset);
+ cm.removeLineClass(line, "wrap", className);
+ }
+
+ /**
+ * Mark a range of text inside the two {line, ch} bounds. Since the range may
+ * be modified, for example, when typing text, this method returns a function
+ * that can be used to remove the mark.
+ */
+ markText(from, to, className = "marked-text") {
+ const cm = editors.get(this);
+ const text = cm.getRange(from, to);
+ const span = cm.getWrapperElement().ownerDocument.createElement("span");
+ span.className = className;
+ span.textContent = text;
+
+ const mark = cm.markText(from, to, { replacedWith: span });
+ return {
+ anchor: span,
+ clear: () => mark.clear(),
+ };
+ }
+
+ /**
+ * Calculates and returns one or more {line, ch} objects for
+ * a zero-based index who's value is relative to the start of
+ * the editor's text.
+ *
+ * If only one argument is given, this method returns a single
+ * {line,ch} object. Otherwise it returns an array.
+ */
+ getPosition(...args) {
+ const cm = editors.get(this);
+ const res = args.map(ind => cm.posFromIndex(ind));
+ return args.length === 1 ? res[0] : res;
+ }
+
+ /**
+ * The reverse of getPosition. Similarly to getPosition this
+ * method returns a single value if only one argument was given
+ * and an array otherwise.
+ */
+ getOffset(...args) {
+ const cm = editors.get(this);
+ const res = args.map(pos => cm.indexFromPos(pos));
+ return args.length > 1 ? res : res[0];
+ }
+
+ /**
+ * Returns a {line, ch} object that corresponds to the
+ * left, top coordinates.
+ */
+ getPositionFromCoords({ left, top }) {
+ const cm = editors.get(this);
+ return cm.coordsChar({ left, top });
+ }
+
+ /**
+ * The reverse of getPositionFromCoords. Similarly, returns a {left, top}
+ * object that corresponds to the specified line and character number.
+ */
+ getCoordsFromPosition({ line, ch }) {
+ const cm = editors.get(this);
+ return cm.charCoords({ line: ~~line, ch: ~~ch });
+ }
+
+ /**
+ * Returns true if there's something to undo and false otherwise.
+ */
+ canUndo() {
+ const cm = editors.get(this);
+ return cm.historySize().undo > 0;
+ }
+
+ /**
+ * Returns true if there's something to redo and false otherwise.
+ */
+ canRedo() {
+ const cm = editors.get(this);
+ return cm.historySize().redo > 0;
+ }
+
+ /**
+ * Marks the contents as clean and returns the current
+ * version number.
+ */
+ setClean() {
+ const cm = editors.get(this);
+ this.version = cm.changeGeneration();
+ this.#lastDirty = false;
+ this.emit("dirty-change");
+ return this.version;
+ }
+
+ /**
+ * Returns true if contents of the text area are
+ * clean i.e. no changes were made since the last version.
+ */
+ isClean() {
+ const cm = editors.get(this);
+ return cm.isClean(this.version);
+ }
+
+ /**
+ * This method opens an in-editor dialog asking for a line to
+ * jump to. Once given, it changes cursor to that line.
+ */
+ jumpToLine() {
+ const doc = editors.get(this).getWrapperElement().ownerDocument;
+ const div = doc.createElement("div");
+ const inp = doc.createElement("input");
+ const txt = doc.createTextNode(L10N.getStr("gotoLineCmd.promptTitle"));
+
+ inp.type = "text";
+ inp.style.width = "10em";
+ inp.style.marginInlineStart = "1em";
+
+ div.appendChild(txt);
+ div.appendChild(inp);
+
+ this.openDialog(div, line => {
+ // Handle LINE:COLUMN as well as LINE
+ const match = line.toString().match(RE_JUMP_TO_LINE);
+ if (match) {
+ const [, matchLine, column] = match;
+ this.setCursor({ line: matchLine - 1, ch: column ? column - 1 : 0 });
+ }
+ });
+ }
+
+ /**
+ * Moves the content of the current line or the lines selected up a line.
+ */
+ moveLineUp() {
+ const cm = editors.get(this);
+ const start = cm.getCursor("start");
+ const end = cm.getCursor("end");
+
+ if (start.line === 0) {
+ return;
+ }
+
+ // Get the text in the lines selected or the current line of the cursor
+ // and append the text of the previous line.
+ let value;
+ if (start.line !== end.line) {
+ value =
+ cm.getRange(
+ { line: start.line, ch: 0 },
+ { line: end.line, ch: cm.getLine(end.line).length }
+ ) + "\n";
+ } else {
+ value = cm.getLine(start.line) + "\n";
+ }
+ value += cm.getLine(start.line - 1);
+
+ // Replace the previous line and the currently selected lines with the new
+ // value and maintain the selection of the text.
+ cm.replaceRange(
+ value,
+ { line: start.line - 1, ch: 0 },
+ { line: end.line, ch: cm.getLine(end.line).length }
+ );
+ cm.setSelection(
+ { line: start.line - 1, ch: start.ch },
+ { line: end.line - 1, ch: end.ch }
+ );
+ }
+
+ /**
+ * Moves the content of the current line or the lines selected down a line.
+ */
+ moveLineDown() {
+ const cm = editors.get(this);
+ const start = cm.getCursor("start");
+ const end = cm.getCursor("end");
+
+ if (end.line + 1 === cm.lineCount()) {
+ return;
+ }
+
+ // Get the text of next line and append the text in the lines selected
+ // or the current line of the cursor.
+ let value = cm.getLine(end.line + 1) + "\n";
+ if (start.line !== end.line) {
+ value += cm.getRange(
+ { line: start.line, ch: 0 },
+ { line: end.line, ch: cm.getLine(end.line).length }
+ );
+ } else {
+ value += cm.getLine(start.line);
+ }
+
+ // Replace the currently selected lines and the next line with the new
+ // value and maintain the selection of the text.
+ cm.replaceRange(
+ value,
+ { line: start.line, ch: 0 },
+ { line: end.line + 1, ch: cm.getLine(end.line + 1).length }
+ );
+ cm.setSelection(
+ { line: start.line + 1, ch: start.ch },
+ { line: end.line + 1, ch: end.ch }
+ );
+ }
+
+ /**
+ * Intercept CodeMirror's Find and replace key shortcut to select the search input
+ */
+ findOrReplace(node, isReplaceAll) {
+ const cm = editors.get(this);
+ const isInput = node.tagName === "INPUT";
+ const isSearchInput = isInput && node.type === "search";
+ // replace box is a different input instance than search, and it is
+ // located in a code mirror dialog
+ const isDialogInput =
+ isInput &&
+ node.parentNode &&
+ node.parentNode.classList.contains("CodeMirror-dialog");
+ if (!(isSearchInput || isDialogInput)) {
+ return;
+ }
+
+ if (isSearchInput || isReplaceAll) {
+ // select the search input
+ // it's the precise reason why we reimplement these key shortcuts
+ node.select();
+ }
+
+ // need to call it since we prevent the propagation of the event and
+ // cancel codemirror's key handling
+ cm.execCommand("find");
+ }
+
+ /**
+ * Intercept CodeMirror's findNext and findPrev key shortcut to allow
+ * immediately search for next occurance after typing a word to search.
+ */
+ findNextOrPrev(node, isFindPrev) {
+ const cm = editors.get(this);
+ const isInput = node.tagName === "INPUT";
+ const isSearchInput = isInput && node.type === "search";
+ if (!isSearchInput) {
+ return;
+ }
+ const query = node.value;
+ // cm.state.search allows to automatically start searching for the next occurance
+ // it's the precise reason why we reimplement these key shortcuts
+ if (!cm.state.search || cm.state.search.query !== query) {
+ cm.state.search = {
+ posFrom: null,
+ posTo: null,
+ overlay: null,
+ query,
+ };
+ }
+
+ // need to call it since we prevent the propagation of the event and
+ // cancel codemirror's key handling
+ if (isFindPrev) {
+ cm.execCommand("findPrev");
+ } else {
+ cm.execCommand("findNext");
+ }
+ }
+
+ /**
+ * Returns current font size for the editor area, in pixels.
+ */
+ getFontSize() {
+ const cm = editors.get(this);
+ const el = cm.getWrapperElement();
+ const win = el.ownerDocument.defaultView;
+
+ return parseInt(win.getComputedStyle(el).getPropertyValue("font-size"), 10);
+ }
+
+ /**
+ * Sets font size for the editor area.
+ */
+ setFontSize(size) {
+ const cm = editors.get(this);
+ cm.getWrapperElement().style.fontSize = parseInt(size, 10) + "px";
+ cm.refresh();
+ }
+
+ /**
+ * Sets an option for the editor. For most options it just defers to
+ * CodeMirror.setOption, but certain ones are maintained within the editor
+ * instance.
+ */
+ setOption(o, v) {
+ const cm = editors.get(this);
+
+ // Save the state of a valid autoCloseBrackets string, so we can reset
+ // it if it gets preffed off and back on.
+ if (o === "autoCloseBrackets" && v) {
+ this.config.autoCloseBracketsSaved = v;
+ }
+
+ if (o === "autocomplete") {
+ this.config.autocomplete = v;
+ this.setupAutoCompletion();
+ } else {
+ cm.setOption(o, v);
+ this.config[o] = v;
+ }
+
+ if (o === "enableCodeFolding") {
+ // The new value maybe explicitly force foldGUtter on or off, ignoring
+ // the prefs service.
+ this.updateCodeFoldingGutter();
+ }
+ }
+
+ /**
+ * Gets an option for the editor. For most options it just defers to
+ * CodeMirror.getOption, but certain ones are maintained within the editor
+ * instance.
+ */
+ getOption(o) {
+ const cm = editors.get(this);
+ if (o === "autocomplete") {
+ return this.config.autocomplete;
+ }
+
+ return cm.getOption(o);
+ }
+
+ /**
+ * Sets up autocompletion for the editor. Lazily imports the required
+ * dependencies because they vary by editor mode.
+ *
+ * Autocompletion is special, because we don't want to automatically use
+ * it just because it is preffed on (it still needs to be requested by the
+ * editor), but we do want to always disable it if it is preffed off.
+ */
+ setupAutoCompletion() {
+ if (!this.config.autocomplete && !this.initializeAutoCompletion) {
+ // Do nothing since there is no autocomplete config and no autocompletion have
+ // been initialized.
+ return;
+ }
+ // The autocomplete module will overwrite this.initializeAutoCompletion
+ // with a mode specific autocompletion handler.
+ if (!this.initializeAutoCompletion) {
+ this.extend(
+ require("resource://devtools/client/shared/sourceeditor/autocomplete.js")
+ );
+ }
+
+ if (this.config.autocomplete && Services.prefs.getBoolPref(AUTOCOMPLETE)) {
+ this.initializeAutoCompletion(this.config.autocompleteOpts);
+ } else {
+ this.destroyAutoCompletion();
+ }
+ }
+
+ getAutoCompletionText() {
+ const cm = editors.get(this);
+ const mark = cm
+ .getAllMarks()
+ .find(m => m.className === AUTOCOMPLETE_MARK_CLASSNAME);
+ if (!mark) {
+ return "";
+ }
+
+ return mark.attributes["data-completion"] || "";
+ }
+
+ setAutoCompletionText(text) {
+ const cursor = this.getCursor();
+ const cm = editors.get(this);
+ const className = AUTOCOMPLETE_MARK_CLASSNAME;
+
+ cm.operation(() => {
+ cm.getAllMarks().forEach(mark => {
+ if (mark.className === className) {
+ mark.clear();
+ }
+ });
+
+ if (text) {
+ cm.markText({ ...cursor, ch: cursor.ch - 1 }, cursor, {
+ className,
+ attributes: {
+ "data-completion": text,
+ },
+ });
+ }
+ });
+ }
+
+ /**
+ * Extends an instance of the Editor object with additional
+ * functions. Each function will be called with context as
+ * the first argument. Context is a {ed, cm} object where
+ * 'ed' is an instance of the Editor object and 'cm' is an
+ * instance of the CodeMirror object. Example:
+ *
+ * function hello(ctx, name) {
+ * let { cm, ed } = ctx;
+ * cm; // CodeMirror instance
+ * ed; // Editor instance
+ * name; // 'Mozilla'
+ * }
+ *
+ * editor.extend({ hello: hello });
+ * editor.hello('Mozilla');
+ */
+ extend(funcs) {
+ Object.keys(funcs).forEach(name => {
+ const cm = editors.get(this);
+ const ctx = { ed: this, cm, Editor };
+
+ if (name === "initialize") {
+ funcs[name](ctx);
+ return;
+ }
+
+ this[name] = funcs[name].bind(null, ctx);
+ });
+ }
+
+ isDestroyed() {
+ return !editors.get(this);
+ }
+
+ destroy() {
+ this.container = null;
+ this.config = null;
+ this.version = null;
+ this.#ownerDoc = null;
+
+ if (this.#prefObserver) {
+ this.#prefObserver.off(KEYMAP_PREF, this.setKeyMap);
+ this.#prefObserver.off(TAB_SIZE, this.reloadPreferences);
+ this.#prefObserver.off(EXPAND_TAB, this.reloadPreferences);
+ this.#prefObserver.off(AUTO_CLOSE, this.reloadPreferences);
+ this.#prefObserver.off(AUTOCOMPLETE, this.reloadPreferences);
+ this.#prefObserver.off(DETECT_INDENT, this.reloadPreferences);
+ this.#prefObserver.off(ENABLE_CODE_FOLDING, this.reloadPreferences);
+ this.#prefObserver.destroy();
+ }
+
+ // Remove the link between the document and code-mirror.
+ const cm = editors.get(this);
+ if (cm?.doc) {
+ cm.doc.cm = null;
+ }
+
+ this.emit("destroy");
+ }
+
+ updateCodeFoldingGutter() {
+ let shouldFoldGutter = this.config.enableCodeFolding;
+ const foldGutterIndex = this.config.gutters.indexOf(
+ "CodeMirror-foldgutter"
+ );
+ const cm = editors.get(this);
+
+ if (shouldFoldGutter === undefined) {
+ shouldFoldGutter = Services.prefs.getBoolPref(ENABLE_CODE_FOLDING);
+ }
+
+ if (shouldFoldGutter) {
+ // Add the gutter before enabling foldGutter
+ if (foldGutterIndex === -1) {
+ const gutters = this.config.gutters.slice();
+ gutters.push("CodeMirror-foldgutter");
+ this.setOption("gutters", gutters);
+ }
+
+ this.setOption("foldGutter", true);
+ } else {
+ // No code should remain folded when folding is off.
+ if (cm) {
+ cm.execCommand("unfoldAll");
+ }
+
+ // Remove the gutter so it doesn't take up space
+ if (foldGutterIndex !== -1) {
+ const gutters = this.config.gutters.slice();
+ gutters.splice(foldGutterIndex, 1);
+ this.setOption("gutters", gutters);
+ }
+
+ this.setOption("foldGutter", false);
+ }
+ }
+
+ /**
+ * Register all key shortcuts.
+ */
+ #initSearchShortcuts(win) {
+ const shortcuts = new KeyShortcuts({
+ window: win,
+ });
+ const keys = ["find.key", "findNext.key", "findPrev.key"];
+
+ if (OS === "Darwin") {
+ keys.push("replaceAllMac.key");
+ } else {
+ keys.push("replaceAll.key");
+ }
+ // Process generic keys:
+ keys.forEach(name => {
+ const key = L10N.getStr(name);
+ shortcuts.on(key, event => this.#onSearchShortcut(name, event));
+ });
+ }
+ /**
+ * Key shortcut listener.
+ */
+ #onSearchShortcut = (name, event) => {
+ if (!this.#isInputOrTextarea(event.target)) {
+ return;
+ }
+ const node = event.originalTarget;
+
+ switch (name) {
+ // replaceAll.key is Alt + find.key
+ case "replaceAllMac.key":
+ this.findOrReplace(node, true);
+ break;
+ // replaceAll.key is Shift + find.key
+ case "replaceAll.key":
+ this.findOrReplace(node, true);
+ break;
+ case "find.key":
+ this.findOrReplace(node, false);
+ break;
+ // findPrev.key is Shift + findNext.key
+ case "findPrev.key":
+ this.findNextOrPrev(node, true);
+ break;
+ case "findNext.key":
+ this.findNextOrPrev(node, false);
+ break;
+ default:
+ console.error("Unexpected editor key shortcut", name);
+ return;
+ }
+ // Prevent default for this action
+ event.stopPropagation();
+ event.preventDefault();
+ };
+
+ /**
+ * Check if a node is an input or textarea
+ */
+ #isInputOrTextarea(element) {
+ const name = element.tagName.toLowerCase();
+ return name === "input" || name === "textarea";
+ }
+}
+
+// Since Editor is a thin layer over CodeMirror some methods
+// are mapped directly—without any changes.
+
+CM_MAPPING.forEach(name => {
+ Editor.prototype[name] = function (...args) {
+ const cm = editors.get(this);
+ return cm[name].apply(cm, args);
+ };
+});
+
+/**
+ * We compute the CSS property names, values, and color names to be used with
+ * CodeMirror to more closely reflect what is supported by the target platform.
+ * The database is used to replace the values used in CodeMirror while initiating
+ * an editor object. This is done here instead of the file codemirror/css.js so
+ * as to leave that file untouched and easily upgradable.
+ */
+function getCSSKeywords(cssProperties) {
+ function keySet(array) {
+ const keys = {};
+ for (let i = 0; i < array.length; ++i) {
+ keys[array[i]] = true;
+ }
+ return keys;
+ }
+
+ const propertyKeywords = cssProperties.getNames();
+ const colorKeywords = {};
+ const valueKeywords = {};
+
+ propertyKeywords.forEach(property => {
+ if (property.includes("color")) {
+ cssProperties.getValues(property).forEach(value => {
+ colorKeywords[value] = true;
+ });
+ } else {
+ cssProperties.getValues(property).forEach(value => {
+ valueKeywords[value] = true;
+ });
+ }
+ });
+
+ return {
+ propertyKeywords: keySet(propertyKeywords),
+ colorKeywords,
+ valueKeywords,
+ };
+}
+
+module.exports = Editor;
diff --git a/devtools/client/shared/sourceeditor/moz.build b/devtools/client/shared/sourceeditor/moz.build
new file mode 100644
index 0000000000..23eb4dbc46
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/moz.build
@@ -0,0 +1,22 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# This Source Code Form is subject to the terms of the Mozilla Public
+# License, v. 2.0. If a copy of the MPL was not distributed with this
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
+
+DIRS += [
+ "codemirror6",
+]
+
+DevToolsModules(
+ "autocomplete.js",
+ "css-autocompleter.js",
+ "editor-commands-controller.js",
+ "editor.js",
+ "wasm.js",
+)
+
+BROWSER_CHROME_MANIFESTS += ["test/browser.toml"]
+
+with Files("**"):
+ BUG_COMPONENT = ("DevTools", "Source Editor")
diff --git a/devtools/client/shared/sourceeditor/package.json b/devtools/client/shared/sourceeditor/package.json
new file mode 100644
index 0000000000..f1eeea83fc
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/package.json
@@ -0,0 +1,26 @@
+{
+ "name": "sourceeditor",
+ "version": "0.0.2",
+ "description": "Build a minified codeMirror bundle including useful addons",
+ "main": "",
+ "scripts": {
+ "build": "webpack",
+ "build-unminified": "webpack --optimization.minimizer=false",
+ "build-cm6": "rollup -c --minified",
+ "build-cm6-unminified": "rollup -c"
+ },
+ "author": "",
+ "license": "",
+ "dependencies": {
+ "codemirror": "6.0.1",
+ "@codemirror/language": "^6.10.0",
+ "@codemirror/lang-javascript": "^6.2.1"
+ },
+ "devDependencies": {
+ "webpack": "^4.28.4",
+ "webpack-cli": "^3.2.1",
+ "rollup": "^4.9.6",
+ "@rollup/plugin-terser": "^0.4.4",
+ "@rollup/plugin-node-resolve": "^15.2.3"
+ }
+}
diff --git a/devtools/client/shared/sourceeditor/rollup.config.mjs b/devtools/client/shared/sourceeditor/rollup.config.mjs
new file mode 100644
index 0000000000..520ca87164
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/rollup.config.mjs
@@ -0,0 +1,24 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+/* eslint-disable import/no-unresolved */
+import terser from "@rollup/plugin-terser";
+import nodeResolve from "@rollup/plugin-node-resolve";
+
+export default function (commandLineArgs) {
+ const plugins = [nodeResolve()];
+ if (commandLineArgs.minified) {
+ plugins.push(terser());
+ }
+
+ return {
+ input: "codemirror6/index.mjs",
+ output: {
+ file: "codemirror6/codemirror6.bundle.js",
+ format: "iife",
+ name: "CodeMirror",
+ },
+ plugins,
+ };
+}
diff --git a/devtools/client/shared/sourceeditor/test/CodeMirrorTestActors.sys.mjs b/devtools/client/shared/sourceeditor/test/CodeMirrorTestActors.sys.mjs
new file mode 100644
index 0000000000..bb0457599b
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/CodeMirrorTestActors.sys.mjs
@@ -0,0 +1,49 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+let gCallback;
+
+export class CodeMirrorTestParent extends JSWindowActorParent {
+ static setCallback(callback) {
+ gCallback = callback;
+ }
+
+ receiveMessage(message) {
+ if (gCallback) {
+ gCallback(message.name, message.data);
+ }
+ }
+}
+
+export class CodeMirrorTestChild extends JSWindowActorChild {
+ handleEvent(event) {
+ if (event.type == "DOMWindowCreated") {
+ this.contentWindow.wrappedJSObject.mozilla_setStatus = (
+ statusMsg,
+ type,
+ customMsg
+ ) => {
+ this.sendAsyncMessage("setStatus", {
+ statusMsg,
+ type,
+ customMsg,
+ });
+ };
+
+ this.check();
+ }
+ }
+
+ check() {
+ const doc = this.contentWindow.document;
+ const out = doc.getElementById("status");
+ if (!out || !out.classList.contains("done")) {
+ this.contentWindow.setTimeout(() => this.check(), 100);
+ return;
+ }
+
+ this.sendAsyncMessage("done", {
+ failed: this.contentWindow.wrappedJSObject.failed,
+ });
+ }
+}
diff --git a/devtools/client/shared/sourceeditor/test/browser.toml b/devtools/client/shared/sourceeditor/test/browser.toml
new file mode 100644
index 0000000000..2c3f5ab374
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/browser.toml
@@ -0,0 +1,70 @@
+[DEFAULT]
+tags = "devtools"
+subsuite = "devtools"
+support-files = [
+ "codemirror/comment_test.js",
+ "codemirror/doc_test.js",
+ "codemirror/driver.js",
+ "codemirror/emacs_test.js",
+ "codemirror/mode_test.css",
+ "codemirror/mode_test.js",
+ "codemirror/multi_test.js",
+ "codemirror/search_test.js",
+ "codemirror/sublime_test.js",
+ "codemirror/test.js",
+ "codemirror/vim_test.js",
+ "codemirror/codemirror.html",
+ "codemirror/vimemacs.html",
+ "codemirror/mode/javascript/test.js",
+ "css_statemachine_testcases.css",
+ "css_statemachine_tests.json",
+ "css_autocompletion_tests.json",
+ "head.js",
+ "head.xhtml",
+ "cm_mode_ruby.js",
+ "cm_script_injection_test.js",
+ "CodeMirrorTestActors.sys.mjs",
+ "!/devtools/client/shared/test/shared-head.js",
+ "!/devtools/client/shared/test/telemetry-test-helpers.js",
+]
+
+["browser_codemirror.js"]
+
+["browser_css_autocompletion.js"]
+
+["browser_css_getInfo.js"]
+
+["browser_css_statemachine.js"]
+
+["browser_detectindent.js"]
+
+["browser_editor_addons.js"]
+
+["browser_editor_alt_b_f.js"]
+
+["browser_editor_autocomplete_basic.js"]
+
+["browser_editor_autocomplete_events.js"]
+
+["browser_editor_basic.js"]
+
+["browser_editor_cursor.js"]
+
+["browser_editor_cursor_blink.js"]
+
+["browser_editor_disableSearchAddon.js"]
+
+["browser_editor_find_again.js"]
+
+["browser_editor_goto_line.js"]
+
+["browser_editor_history.js"]
+
+["browser_editor_markers.js"]
+
+["browser_editor_movelines.js"]
+
+["browser_editor_prefs.js"]
+
+["browser_vimemacs.js"]
+skip-if = ["os == 'linux' && debug"] # bug 981707
diff --git a/devtools/client/shared/sourceeditor/test/browser_codemirror.js b/devtools/client/shared/sourceeditor/test/browser_codemirror.js
new file mode 100644
index 0000000000..ca19c20d9f
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/browser_codemirror.js
@@ -0,0 +1,33 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const URI =
+ "chrome://mochitests/content/browser/devtools/client/shared/sourceeditor/" +
+ "test/codemirror/codemirror.html";
+
+add_task(async function test() {
+ requestLongerTimeout(3);
+
+ /*
+ * In devtools/client/shared/sourceeditor/test/codemirror/search_test.js there is a test
+ * multilineInsensitiveSlow which assumes an operation takes less than 100ms.
+ * With a precision of 100ms, if we get unlikely and begin execution towards the
+ * end of one spot (e.g. at 95 ms) we will clamp down, take (e.g.) 10ms to execute
+ * and it will appear to take 100ms.
+ *
+ * To avoid this, we hardcode to 2ms of precision.
+ *
+ * In theory we don't need to set the pref for all of CodeMirror, in practice
+ * it seems very difficult to set a pref for just one of the tests.
+ */
+ await SpecialPowers.pushPrefEnv({
+ set: [
+ ["privacy.reduceTimerPrecision", true],
+ ["privacy.resistFingerprinting.reduceTimerPrecision.microseconds", 2000],
+ ],
+ });
+
+ await runCodeMirrorTest(URI);
+});
diff --git a/devtools/client/shared/sourceeditor/test/browser_css_autocompletion.js b/devtools/client/shared/sourceeditor/test/browser_css_autocompletion.js
new file mode 100644
index 0000000000..768dbe1ac7
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/browser_css_autocompletion.js
@@ -0,0 +1,172 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const CSSCompleter = require("resource://devtools/client/shared/sourceeditor/css-autocompleter.js");
+
+const CSS_URI =
+ "http://mochi.test:8888/browser/devtools/client/shared/sourceeditor" +
+ "/test/css_statemachine_testcases.css";
+const TESTS_URI =
+ "http://mochi.test:8888/browser/devtools/client" +
+ "/shared/sourceeditor/test/css_autocompletion_tests.json";
+
+const source = read(CSS_URI);
+const { tests } = JSON.parse(read(TESTS_URI));
+
+const TEST_URI =
+ "data:text/html;charset=UTF-8," +
+ encodeURIComponent(
+ [
+ "<!DOCTYPE html>",
+ "<html>",
+ " <head>",
+ " <title>CSS State machine tests.</title>",
+ " <style type='text/css'>",
+ "#progress {",
+ " width: 500px; height: 30px;",
+ " border: 1px solid black;",
+ " position: relative",
+ "}",
+ "#progress div {",
+ " width: 0%; height: 100%;",
+ " background: green;",
+ " position: absolute;",
+ " z-index: -1; top: 0",
+ "}",
+ "#progress.failed div {",
+ " background: red !important;",
+ "}",
+ "#progress.failed:after {",
+ " content: 'Some tests failed';",
+ " color: white",
+ "}",
+ "#progress:before {",
+ " content: 'Running test ' attr(data-progress) ' of " +
+ tests.length +
+ "';",
+ " color: white;",
+ " text-shadow: 0 0 2px darkgreen;",
+ "}",
+ " </style>",
+ " </head>",
+ " <body>",
+ " <h2>State machine tests for CSS autocompleter.</h2><br>",
+ " <div id='progress' data-progress='0'>",
+ " <div></div>",
+ " </div>",
+ " <div id='devtools-menu' class='devtools-toolbarbutton'></div>",
+ " <div id='devtools-toolbarbutton' class='devtools-menulist'></div>",
+ " <div id='devtools-anotherone'></div>",
+ " <div id='devtools-yetagain'></div>",
+ " <div id='devtools-itjustgoeson'></div>",
+ " <div id='devtools-okstopitnow'></div>",
+ " <div class='hidden-labels-box devtools-toolbarbutton devtools-menulist'></div>",
+ " <div class='devtools-menulist'></div>",
+ " <div class='devtools-menulist'></div>",
+ /* eslint-disable max-len */
+ " <tabs class='devtools-toolbarbutton'><tab></tab><tab></tab><tab></tab></tabs><tabs></tabs>",
+ /* eslint-enable max-len */
+ " <button class='category-name visible'></button>",
+ " <div class='devtools-toolbarbutton' label='true'>",
+ " <hbox class='toolbarbutton-menubutton-button'></hbox></div>",
+ " </body>",
+ " </html>",
+ ].join("\n")
+ );
+
+let browser;
+let index = 0;
+let completer = null;
+let inspector;
+
+add_task(async function test() {
+ const tab = await addTab(TEST_URI);
+ browser = tab.linkedBrowser;
+ await runTests();
+ browser = null;
+ gBrowser.removeCurrentTab();
+});
+
+async function runTests() {
+ const target = await createAndAttachTargetForTab(gBrowser.selectedTab);
+ inspector = await target.getFront("inspector");
+ const walker = inspector.walker;
+ const cssPropertiesFront = await target.getFront("cssProperties");
+ completer = new CSSCompleter({
+ walker,
+ cssProperties: cssPropertiesFront.cssProperties,
+ });
+ await checkStateAndMoveOn();
+ await completer.walker.release();
+ await target.destroy();
+ inspector = null;
+ completer = null;
+}
+
+async function checkStateAndMoveOn() {
+ if (index == tests.length) {
+ return;
+ }
+
+ const [lineCh, expectedSuggestions] = tests[index];
+ const [line, ch] = lineCh;
+
+ ++index;
+ await SpecialPowers.spawn(
+ browser,
+ [[index, tests.length]],
+ function ([idx, len]) {
+ const progress = content.document.getElementById("progress");
+ const progressDiv = content.document.querySelector("#progress > div");
+ progress.dataset.progress = idx;
+ progressDiv.style.width = (100 * idx) / len + "%";
+ }
+ );
+
+ const actualSuggestions = await completer.complete(limit(source, lineCh), {
+ line,
+ ch,
+ });
+ await checkState(expectedSuggestions, actualSuggestions);
+ await checkStateAndMoveOn();
+}
+
+async function checkState(expected, actual) {
+ if (expected.length != actual.length) {
+ ok(
+ false,
+ "Number of suggestions did not match up for state " +
+ index +
+ ". Expected: " +
+ expected.length +
+ ", Actual: " +
+ actual.length
+ );
+ await SpecialPowers.spawn(browser, [], function () {
+ const progress = content.document.getElementById("progress");
+ progress.classList.add("failed");
+ });
+ return;
+ }
+
+ for (let i = 0; i < actual.length; i++) {
+ if (expected[i] != actual[i].label) {
+ ok(
+ false,
+ "Suggestion " +
+ i +
+ " of state " +
+ index +
+ " did not match up" +
+ ". Expected: " +
+ expected[i] +
+ ". Actual: " +
+ actual[i].label
+ );
+ return;
+ }
+ }
+ ok(true, "Test " + index + " passed. ");
+}
diff --git a/devtools/client/shared/sourceeditor/test/browser_css_getInfo.js b/devtools/client/shared/sourceeditor/test/browser_css_getInfo.js
new file mode 100644
index 0000000000..c4d9385edf
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/browser_css_getInfo.js
@@ -0,0 +1,250 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const CSSCompleter = require("resource://devtools/client/shared/sourceeditor/css-autocompleter.js");
+
+const source = [
+ ".devtools-toolbar {",
+ " -moz-appearance: none;",
+ " padding:4px 3px;border-bottom-width: 1px;",
+ " border-bottom-style: solid;",
+ "}",
+ "",
+ "#devtools-menu.devtools-menulist,",
+ ".devtools-toolbarbutton#devtools-menu {",
+ " -moz-appearance: none;",
+ " align-items: center;",
+ " min-width: 78px;",
+ " min-height: 22px;",
+ " text-shadow: 0 -1px 0 hsla(210,8%,5%,.45);",
+ " border: 1px solid hsla(210,8%,5%,.45);",
+ " border-radius: 3px;",
+ " background: linear-gradient(hsla(212,7%,57%,.35),",
+ " hsla(212,7%,57%,.1)) padding-box;",
+ " margin: 0 3px;",
+ " color: inherit;",
+ "}",
+ "",
+ ".devtools-toolbarbutton > hbox.toolbarbutton-menubutton-button {",
+ " flex-direction: row;",
+ "}",
+ "",
+ ".devtools-menulist:active,",
+ "#devtools-toolbarbutton:focus {",
+ " outline: 1px dotted hsla(210,30%,85%,0.7);",
+ " outline-offset : -4px;",
+ "}",
+ "",
+ ".devtools-toolbarbutton:not([label]) {",
+ " min-width: 32px;",
+ "}",
+ "",
+ ".devtools-toolbarbutton:not([label]) > .toolbarbutton-text, .devtools-toolbar {",
+ " display: none;",
+ "}",
+].join("\n");
+
+// Format of test cases :
+// [
+// {line, ch}, - The caret position at which the getInfo call should be made
+// expectedState, - The expected state at the caret
+// expectedSelector, - The expected selector for the state
+// expectedProperty, - The expected property name for states value and property
+// expectedValue, - If state is value, then the expected value
+// ]
+
+/* eslint-disable max-len */
+const tests = [
+ [{ line: 0, ch: 13 }, "selector", ".devtools-toolbar"],
+ [
+ { line: 8, ch: 13 },
+ "property",
+ [
+ "#devtools-menu.devtools-menulist",
+ ".devtools-toolbarbutton#devtools-menu ",
+ ],
+ "-moz-appearance",
+ ],
+ [
+ { line: 28, ch: 25 },
+ "value",
+ [".devtools-menulist:active", "#devtools-toolbarbutton:focus "],
+ "outline-offset",
+ "-4px",
+ ],
+ [{ line: 4, ch: 1 }, "null"],
+ [{ line: 5, ch: 0 }, "null"],
+ [{ line: 31, ch: 13 }, "selector", ".devtools-toolbarbutton:not([label])"],
+ [
+ { line: 35, ch: 23 },
+ "selector",
+ ".devtools-toolbarbutton:not([label]) > .toolbarbutton-text",
+ ],
+ [{ line: 35, ch: 70 }, "selector", ".devtools-toolbar"],
+ [
+ { line: 27, ch: 14 },
+ "value",
+ [".devtools-menulist:active", "#devtools-toolbarbutton:focus "],
+ "outline",
+ "1px dotted hsla(210,30%,85%,0.7)",
+ ],
+ [
+ { line: 16, ch: 16 },
+ "value",
+ [
+ "#devtools-menu.devtools-menulist",
+ ".devtools-toolbarbutton#devtools-menu ",
+ ],
+ "background",
+ "linear-gradient(hsla(212,7%,57%,.35),\n hsla(212,7%,57%,.1)) padding-box",
+ ],
+ [
+ { line: 16, ch: 3 },
+ "value",
+ [
+ "#devtools-menu.devtools-menulist",
+ ".devtools-toolbarbutton#devtools-menu ",
+ ],
+ "background",
+ "linear-gradient(hsla(212,7%,57%,.35),\n hsla(212,7%,57%,.1)) padding-box",
+ ],
+ [
+ { line: 15, ch: 25 },
+ "value",
+ [
+ "#devtools-menu.devtools-menulist",
+ ".devtools-toolbarbutton#devtools-menu ",
+ ],
+ "background",
+ "linear-gradient(hsla(212,7%,57%,.35),\n hsla(212,7%,57%,.1)) padding-box",
+ ],
+];
+/* eslint-enable max-len */
+
+const TEST_URI =
+ "data:text/html;charset=UTF-8," +
+ encodeURIComponent(
+ [
+ "<!DOCTYPE html>",
+ "<html>",
+ " <head>",
+ " <title>CSS contextual information tests.</title>",
+ " <style type='text/css'>",
+ "#progress {",
+ " width: 500px; height: 30px;",
+ " border: 1px solid black;",
+ " position: relative",
+ "}",
+ "#progress div {",
+ " width: 0%; height: 100%;",
+ " background: green;",
+ " position: absolute;",
+ " z-index: -1; top: 0",
+ "}",
+ "#progress.failed div {",
+ " background: red !important;",
+ "}",
+ "#progress.failed:after {",
+ " content: 'Some tests failed';",
+ " color: white",
+ "}",
+ "#progress:before {",
+ " content: 'Running test ' attr(data-progress) ' of " +
+ tests.length +
+ "';",
+ " color: white;",
+ " text-shadow: 0 0 2px darkgreen;",
+ "}",
+ " </style>",
+ " </head>",
+ " <body>",
+ " <h2>State machine tests for CSS autocompleter.</h2><br>",
+ " <div id='progress' data-progress='0'>",
+ " <div></div>",
+ " </div>",
+ " </body>",
+ " </html>",
+ ].join("\n")
+ );
+
+add_task(async function test() {
+ const tab = await addTab(TEST_URI);
+ const browser = tab.linkedBrowser;
+
+ const completer = new CSSCompleter({
+ cssProperties: getClientCssProperties(),
+ });
+ const matches = (arr, toCheck) => !arr.some((x, i) => x != toCheck[i]);
+ const checkState = (expected, actual) => {
+ if (expected[0] == "null" && actual == null) {
+ return true;
+ } else if (
+ expected[0] == actual.state &&
+ expected[0] == "selector" &&
+ expected[1] == actual.selector
+ ) {
+ return true;
+ } else if (
+ expected[0] == actual.state &&
+ expected[0] == "property" &&
+ matches(expected[1], actual.selectors) &&
+ expected[2] == actual.propertyName
+ ) {
+ return true;
+ } else if (
+ expected[0] == actual.state &&
+ expected[0] == "value" &&
+ matches(expected[1], actual.selectors) &&
+ expected[2] == actual.propertyName &&
+ expected[3] == actual.value
+ ) {
+ return true;
+ }
+ return false;
+ };
+
+ let i = 0;
+ for (const expected of tests) {
+ ++i;
+ const caret = expected.splice(0, 1)[0];
+ await SpecialPowers.spawn(
+ browser,
+ [[i, tests.length]],
+ function ([idx, len]) {
+ const progress = content.document.getElementById("progress");
+ const progressDiv = content.document.querySelector("#progress > div");
+ progress.dataset.progress = idx;
+ progressDiv.style.width = (100 * idx) / len + "%";
+ }
+ );
+ const actual = completer.getInfoAt(source, caret);
+ if (checkState(expected, actual)) {
+ ok(true, "Test " + i + " passed. ");
+ } else {
+ ok(
+ false,
+ "Test " +
+ i +
+ " failed. Expected state : [" +
+ expected +
+ "] " +
+ "but found [" +
+ actual.state +
+ ", " +
+ (actual.selector || actual.selectors) +
+ ", " +
+ actual.propertyName +
+ ", " +
+ actual.value +
+ "]."
+ );
+ await SpecialPowers.spawn(browser, [], function () {
+ const progress = content.document.getElementById("progress");
+ progress.classList.add("failed");
+ });
+ }
+ }
+ gBrowser.removeCurrentTab();
+});
diff --git a/devtools/client/shared/sourceeditor/test/browser_css_statemachine.js b/devtools/client/shared/sourceeditor/test/browser_css_statemachine.js
new file mode 100644
index 0000000000..103322904f
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/browser_css_statemachine.js
@@ -0,0 +1,144 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const CSSCompleter = require("resource://devtools/client/shared/sourceeditor/css-autocompleter.js");
+
+const CSS_URI =
+ "http://mochi.test:8888/browser/devtools/client/shared/sourceeditor" +
+ "/test/css_statemachine_testcases.css";
+const TESTS_URI =
+ "http://mochi.test:8888/browser/devtools/client" +
+ "/shared/sourceeditor/test/css_statemachine_tests.json";
+
+const source = read(CSS_URI);
+const { tests } = JSON.parse(read(TESTS_URI));
+
+const TEST_URI =
+ "data:text/html;charset=UTF-8," +
+ encodeURIComponent(
+ [
+ "<!DOCTYPE html>",
+ "<html>",
+ " <head>",
+ " <title>CSS State machine tests.</title>",
+ " <style type='text/css'>",
+ "#progress {",
+ " width: 500px; height: 30px;",
+ " border: 1px solid black;",
+ " position: relative",
+ "}",
+ "#progress div {",
+ " width: 0%; height: 100%;",
+ " background: green;",
+ " position: absolute;",
+ " z-index: -1; top: 0",
+ "}",
+ "#progress.failed div {",
+ " background: red !important;",
+ "}",
+ "#progress.failed:after {",
+ " content: 'Some tests failed';",
+ " color: white",
+ "}",
+ "#progress:before {",
+ " content: 'Running test ' attr(data-progress) ' of " +
+ tests.length +
+ "';",
+ " color: white;",
+ " text-shadow: 0 0 2px darkgreen;",
+ "}",
+ " </style>",
+ " </head>",
+ " <body>",
+ " <h2>State machine tests for CSS autocompleter.</h2><br>",
+ " <div id='progress' data-progress='0'>",
+ " <div></div>",
+ " </div>",
+ " </body>",
+ " </html>",
+ ].join("\n")
+ );
+
+add_task(async function test() {
+ const tab = await addTab(TEST_URI);
+ const browser = tab.linkedBrowser;
+
+ const completer = new CSSCompleter({
+ cssProperties: getClientCssProperties(),
+ });
+ const checkState = state => {
+ if (state[0] == "null" && (!completer.state || completer.state == "null")) {
+ return true;
+ } else if (
+ state[0] == completer.state &&
+ state[0] == "selector" &&
+ state[1] == completer.selectorState &&
+ state[2] == completer.completing &&
+ state[3] == completer.selector
+ ) {
+ return true;
+ } else if (
+ state[0] == completer.state &&
+ state[0] == "value" &&
+ state[2] == completer.completing &&
+ state[3] == completer.propertyName
+ ) {
+ return true;
+ } else if (
+ state[0] == completer.state &&
+ state[2] == completer.completing &&
+ state[0] != "selector" &&
+ state[0] != "value"
+ ) {
+ return true;
+ }
+ return false;
+ };
+
+ let i = 0;
+ for (const testcase of tests) {
+ ++i;
+ await SpecialPowers.spawn(
+ browser,
+ [[i, tests.length]],
+ function ([idx, len]) {
+ const progress = content.document.getElementById("progress");
+ const progressDiv = content.document.querySelector("#progress > div");
+ progress.dataset.progress = idx;
+ progressDiv.style.width = (100 * idx) / len + "%";
+ }
+ );
+ completer.resolveState(limit(source, testcase[0]), {
+ line: testcase[0][0],
+ ch: testcase[0][1],
+ });
+ if (checkState(testcase[1])) {
+ ok(true, "Test " + i + " passed. ");
+ } else {
+ ok(
+ false,
+ "Test " +
+ i +
+ " failed. Expected state : [" +
+ testcase[1] +
+ "] " +
+ "but found [" +
+ completer.state +
+ ", " +
+ completer.selectorState +
+ ", " +
+ completer.completing +
+ ", " +
+ (completer.propertyName || completer.selector) +
+ "]."
+ );
+ await SpecialPowers.spawn(browser, [], function () {
+ const progress = content.document.getElementById("progress");
+ progress.classList.add("failed");
+ });
+ }
+ }
+ gBrowser.removeCurrentTab();
+});
diff --git a/devtools/client/shared/sourceeditor/test/browser_detectindent.js b/devtools/client/shared/sourceeditor/test/browser_detectindent.js
new file mode 100644
index 0000000000..80f2487417
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/browser_detectindent.js
@@ -0,0 +1,99 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const TWO_SPACES_CODE = [
+ "/*",
+ " * tricky comment block",
+ " */",
+ "div {",
+ " color: red;",
+ " background: blue;",
+ "}",
+ " ",
+ "span {",
+ " padding-left: 10px;",
+ "}",
+].join("\n");
+
+const FOUR_SPACES_CODE = [
+ "var obj = {",
+ " addNumbers: function() {",
+ " var x = 5;",
+ " var y = 18;",
+ " return x + y;",
+ " },",
+ " ",
+ " /*",
+ " * Do some stuff to two numbers",
+ " * ",
+ " * @param x",
+ " * @param y",
+ " * ",
+ " * @return the result of doing stuff",
+ " */",
+ " subtractNumbers: function(x, y) {",
+ " var x += 7;",
+ " var y += 18;",
+ " var result = x - y;",
+ " result %= 2;",
+ " }",
+ "}",
+].join("\n");
+
+const TABS_CODE = [
+ "/*",
+ " * tricky comment block",
+ " */",
+ "div {",
+ "\tcolor: red;",
+ "\tbackground: blue;",
+ "}",
+ "",
+ "span {",
+ "\tpadding-left: 10px;",
+ "}",
+].join("\n");
+
+const NONE_CODE = [
+ "var x = 0;",
+ " // stray thing",
+ "var y = 9;",
+ " ",
+ "",
+].join("\n");
+
+async function test() {
+ waitForExplicitFinish();
+
+ const { ed, win } = await setup();
+ is(ed.getOption("indentUnit"), 2, "2 spaces before code added");
+ is(ed.getOption("indentWithTabs"), false, "spaces is default");
+
+ ed.setText(NONE_CODE);
+ is(ed.getOption("indentUnit"), 2, "2 spaces after un-detectable code");
+ is(
+ ed.getOption("indentWithTabs"),
+ false,
+ "spaces still set after un-detectable code"
+ );
+
+ ed.setText(FOUR_SPACES_CODE);
+ is(ed.getOption("indentUnit"), 4, "4 spaces detected in 4 space code");
+ is(ed.getOption("indentWithTabs"), false, "spaces detected in 4 space code");
+
+ ed.setText(TWO_SPACES_CODE);
+ is(ed.getOption("indentUnit"), 2, "2 spaces detected in 2 space code");
+ is(ed.getOption("indentWithTabs"), false, "spaces detected in 2 space code");
+
+ ed.setText(TABS_CODE);
+ is(ed.getOption("indentUnit"), 2, "2 space indentation unit");
+ is(
+ ed.getOption("indentWithTabs"),
+ true,
+ "tabs detected in majority tabs code"
+ );
+
+ teardown(ed, win);
+}
diff --git a/devtools/client/shared/sourceeditor/test/browser_editor_addons.js b/devtools/client/shared/sourceeditor/test/browser_editor_addons.js
new file mode 100644
index 0000000000..85aec38ec3
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/browser_editor_addons.js
@@ -0,0 +1,33 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+async function test() {
+ waitForExplicitFinish();
+
+ const { ed, win } = await setup();
+ const doc = win.document.querySelector("iframe").contentWindow.document;
+
+ // trailingspace.js
+ ed.setText("Hello ");
+ ed.setOption("showTrailingSpace", false);
+ ok(!doc.querySelector(".cm-trailingspace"));
+ ed.setOption("showTrailingSpace", true);
+ ok(doc.querySelector(".cm-trailingspace"));
+
+ // foldcode.js and foldgutter.js
+ ed.setMode(Editor.modes.js);
+ ed.setText("function main() {\nreturn 'Hello, World!';\n}");
+ executeSoon(() => testFold(doc, ed, win));
+}
+
+function testFold(doc, ed, win) {
+ // Wait until folding arrow is there.
+ if (!doc.querySelector(".CodeMirror-foldgutter-open")) {
+ executeSoon(() => testFold(doc, ed, win));
+ return;
+ }
+
+ teardown(ed, win);
+}
diff --git a/devtools/client/shared/sourceeditor/test/browser_editor_alt_b_f.js b/devtools/client/shared/sourceeditor/test/browser_editor_alt_b_f.js
new file mode 100644
index 0000000000..cacefd8dac
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/browser_editor_alt_b_f.js
@@ -0,0 +1,46 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+// Ensure Alt-B and Alt-F keyboard shortcuts work as expected in the source editor.
+// See Bug 1481443.
+
+add_task(async function () {
+ const { ed, win } = await setup();
+ const editorDoc = ed.container.contentDocument;
+ await promiseWaitForFocus();
+ const isMacOS = Services.appinfo.OS === "Darwin";
+
+ ed.focus();
+
+ const initialText = "a b c d e";
+ ed.setText(initialText);
+
+ ed.setCursor({ line: 1, ch: initialText.length });
+
+ EventUtils.synthesizeKey("b", { altKey: true }, editorDoc.defaultView);
+
+ // A character is added only on OSX.
+ let expectedText = isMacOS ? initialText + "b" : initialText;
+ is(
+ ed.getCursor().ch,
+ expectedText.length,
+ "Cursor is at expected position after Alt-B"
+ );
+ is(ed.getText(), expectedText, "Editor has expected content after Alt-B");
+
+ EventUtils.synthesizeKey("f", { altKey: true }, editorDoc.defaultView);
+
+ // A character is added only on OSX.
+ expectedText = isMacOS ? expectedText + "f" : initialText;
+ is(
+ ed.getCursor().ch,
+ expectedText.length,
+ "Cursor is at expected position after Alt-F"
+ );
+ is(ed.getText(), expectedText, "Editor has expected content after Alt-F");
+
+ ed.destroy();
+ win.close();
+});
diff --git a/devtools/client/shared/sourceeditor/test/browser_editor_autocomplete_basic.js b/devtools/client/shared/sourceeditor/test/browser_editor_autocomplete_basic.js
new file mode 100644
index 0000000000..c7dc9c8a97
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/browser_editor_autocomplete_basic.js
@@ -0,0 +1,51 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const AUTOCOMPLETION_PREF = "devtools.editor.autocomplete";
+
+// Test to make sure that different autocompletion modes can be created,
+// switched, and destroyed. This doesn't test the actual autocompletion
+// popups, only their integration with the editor.
+async function test() {
+ waitForExplicitFinish();
+ const { ed, win } = await setup();
+ const edWin = ed.container.contentWindow.wrappedJSObject;
+ testJS(ed, edWin);
+ testCSS(ed, edWin);
+ testPref(ed, edWin);
+ teardown(ed, win);
+}
+
+function testJS(ed, win) {
+ ok(!ed.getOption("autocomplete"), "Autocompletion is not set");
+
+ ed.setMode(Editor.modes.js);
+ ed.setOption("autocomplete", true);
+
+ ok(ed.getOption("autocomplete"), "Autocompletion is set");
+}
+
+function testCSS(ed, win) {
+ ok(ed.getOption("autocomplete"), "Autocompletion is set");
+
+ ed.setMode(Editor.modes.css);
+ ed.setOption("autocomplete", true);
+
+ ok(ed.getOption("autocomplete"), "Autocompletion is still set");
+}
+
+function testPref(ed, win) {
+ ed.setMode(Editor.modes.js);
+ ed.setOption("autocomplete", true);
+
+ ok(ed.getOption("autocomplete"), "Autocompletion is set");
+
+ info("Preffing autocompletion off");
+ Services.prefs.setBoolPref(AUTOCOMPLETION_PREF, false);
+
+ ok(ed.getOption("autocomplete"), "Autocompletion is still set");
+
+ Services.prefs.clearUserPref(AUTOCOMPLETION_PREF);
+}
diff --git a/devtools/client/shared/sourceeditor/test/browser_editor_autocomplete_events.js b/devtools/client/shared/sourceeditor/test/browser_editor_autocomplete_events.js
new file mode 100644
index 0000000000..88fbcdbf1d
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/browser_editor_autocomplete_events.js
@@ -0,0 +1,158 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const TEST_URI =
+ "data:text/html;charset=UTF-8,<html><body><bar></bar>" +
+ "<div id='baz'></div><body></html>";
+
+add_task(async function () {
+ await addTab(TEST_URI);
+ await runTests();
+});
+
+async function runTests() {
+ const target = await createAndAttachTargetForTab(gBrowser.selectedTab);
+ const inspector = await target.getFront("inspector");
+ const walker = inspector.walker;
+ const cssPropertiesFront = await target.getFront("cssProperties");
+ const { ed, win, edWin } = await setup({
+ autocomplete: true,
+ mode: Editor.modes.css,
+ autocompleteOpts: {
+ walker,
+ cssProperties: cssPropertiesFront.cssProperties,
+ },
+ });
+ await testMouse(ed, edWin);
+ await testKeyboard(ed, edWin);
+ await testKeyboardCycle(ed, edWin);
+ await testKeyboardCycleForPrefixedString(ed, edWin);
+ await testKeyboardCSSComma(ed, edWin);
+ await testCloseOnEscape(ed, edWin);
+ teardown(ed, win);
+}
+
+async function testKeyboard(ed, win) {
+ ed.focus();
+ ed.setText("b");
+ ed.setCursor({ line: 1, ch: 1 });
+
+ const popupOpened = ed.getAutocompletionPopup().once("popup-opened");
+
+ const autocompleteKey = Editor.keyFor("autocompletion", {
+ noaccel: true,
+ }).toUpperCase();
+ EventUtils.synthesizeKey("VK_" + autocompleteKey, { ctrlKey: true }, win);
+
+ info("Waiting for popup to be opened");
+ await popupOpened;
+
+ EventUtils.synthesizeKey("VK_RETURN", {}, win);
+ is(ed.getText(), "bar", "Editor text has been updated");
+}
+
+async function testKeyboardCycle(ed, win) {
+ ed.focus();
+ ed.setText("b");
+ ed.setCursor({ line: 1, ch: 1 });
+
+ const popupOpened = ed.getAutocompletionPopup().once("popup-opened");
+
+ const autocompleteKey = Editor.keyFor("autocompletion", {
+ noaccel: true,
+ }).toUpperCase();
+ EventUtils.synthesizeKey("VK_" + autocompleteKey, { ctrlKey: true }, win);
+
+ info("Waiting for popup to be opened");
+ await popupOpened;
+
+ EventUtils.synthesizeKey("VK_DOWN", {}, win);
+ is(ed.getText(), "bar", "Editor text has been updated");
+
+ EventUtils.synthesizeKey("VK_DOWN", {}, win);
+ is(ed.getText(), "body", "Editor text has been updated");
+
+ EventUtils.synthesizeKey("VK_DOWN", {}, win);
+ is(ed.getText(), "#baz", "Editor text has been updated");
+}
+
+async function testKeyboardCycleForPrefixedString(ed, win) {
+ ed.focus();
+ ed.setText("#b");
+ ed.setCursor({ line: 1, ch: 2 });
+
+ const popupOpened = ed.getAutocompletionPopup().once("popup-opened");
+
+ const autocompleteKey = Editor.keyFor("autocompletion", {
+ noaccel: true,
+ }).toUpperCase();
+ EventUtils.synthesizeKey("VK_" + autocompleteKey, { ctrlKey: true }, win);
+
+ info("Waiting for popup to be opened");
+ await popupOpened;
+
+ EventUtils.synthesizeKey("VK_DOWN", {}, win);
+ is(ed.getText(), "#baz", "Editor text has been updated");
+}
+
+async function testKeyboardCSSComma(ed, win) {
+ ed.focus();
+ ed.setText("b");
+ ed.setCursor({ line: 1, ch: 1 });
+
+ let isPopupOpened = false;
+ const popupOpened = ed.getAutocompletionPopup().once("popup-opened");
+ popupOpened.then(() => {
+ isPopupOpened = true;
+ });
+
+ EventUtils.synthesizeKey(",", {}, win);
+
+ await wait(500);
+
+ ok(!isPopupOpened, "Autocompletion shouldn't be opened");
+}
+
+async function testMouse(ed, win) {
+ ed.focus();
+ ed.setText("b");
+ ed.setCursor({ line: 1, ch: 1 });
+
+ const popupOpened = ed.getAutocompletionPopup().once("popup-opened");
+
+ const autocompleteKey = Editor.keyFor("autocompletion", {
+ noaccel: true,
+ }).toUpperCase();
+ EventUtils.synthesizeKey("VK_" + autocompleteKey, { ctrlKey: true }, win);
+
+ info("Waiting for popup to be opened");
+ await popupOpened;
+ ed.getAutocompletionPopup()._list.children[2].click();
+ is(ed.getText(), "#baz", "Editor text has been updated");
+}
+
+async function testCloseOnEscape(ed, win) {
+ ed.focus();
+ ed.setText("b");
+ ed.setCursor({ line: 1, ch: 1 });
+
+ const popupOpened = ed.getAutocompletionPopup().once("popup-opened");
+
+ const autocompleteKey = Editor.keyFor("autocompletion", {
+ noaccel: true,
+ }).toUpperCase();
+ EventUtils.synthesizeKey("VK_" + autocompleteKey, { ctrlKey: true }, win);
+
+ info("Waiting for popup to be opened");
+ await popupOpened;
+
+ is(ed.getAutocompletionPopup().isOpen, true, "The popup is open");
+
+ const popupClosed = ed.getAutocompletionPopup().once("popup-closed");
+ EventUtils.synthesizeKey("VK_ESCAPE", {}, win);
+
+ await popupClosed;
+ is(ed.getAutocompletionPopup().isOpen, false, "Escape key closed popup");
+}
diff --git a/devtools/client/shared/sourceeditor/test/browser_editor_basic.js b/devtools/client/shared/sourceeditor/test/browser_editor_basic.js
new file mode 100644
index 0000000000..9373990bf7
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/browser_editor_basic.js
@@ -0,0 +1,75 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+async function test() {
+ waitForExplicitFinish();
+ const { ed, win } = await setup();
+ // appendTo
+ const cmFrame = win.document.querySelector("iframe");
+ const cmStyle = cmFrame.contentDocument.getElementById("cmBaseStyle");
+ ok(~cmStyle.innerHTML.indexOf(".CodeMirror"), "correct iframe is there");
+
+ // getOption/setOption
+ ok(ed.getOption("styleActiveLine"), "getOption works");
+ ed.setOption("styleActiveLine", false);
+ ok(!ed.getOption("styleActiveLine"), "setOption works");
+
+ // Language modes
+ is(ed.getMode(), Editor.modes.text, "getMode");
+ ed.setMode(Editor.modes.js);
+ is(ed.getMode(), Editor.modes.js, "setMode");
+
+ // Content
+ is(ed.getText(), "Hello.", "getText");
+ ed.setText("Hi.\nHow are you?");
+ is(ed.getText(), "Hi.\nHow are you?", "setText");
+ is(ed.getText(1), "How are you?", "getText(num)");
+ is(ed.getText(5), "", "getText(num) when num is out of scope");
+
+ ed.replaceText("YOU", { line: 1, ch: 8 }, { line: 1, ch: 11 });
+ is(ed.getText(1), "How are YOU?", "replaceText(str, from, to)");
+ ed.replaceText("you?", { line: 1, ch: 8 });
+ is(ed.getText(1), "How are you?", "replaceText(str, from)");
+ ed.replaceText("Hello.");
+ is(ed.getText(), "Hello.", "replaceText(str)");
+
+ ed.insertText(", sir/madam", { line: 0, ch: 5 });
+ is(ed.getText(), "Hello, sir/madam.", "insertText");
+
+ // Add-ons
+ ed.extend({ whoami: () => "Anton", whereami: () => "Mozilla" });
+ is(ed.whoami(), "Anton", "extend/1");
+ is(ed.whereami(), "Mozilla", "extend/2");
+
+ // Line classes
+ ed.setText("Hello!\nHow are you?");
+ ok(!ed.hasLineClass(0, "test"), "no test line class");
+ ed.addLineClass(0, "test");
+ ok(ed.hasLineClass(0, "test"), "test line class is there");
+ ed.removeLineClass(0, "test");
+ ok(!ed.hasLineClass(0, "test"), "test line class is gone");
+
+ // Font size
+ const size = ed.getFontSize();
+ is("number", typeof size, "we have the default font size");
+ ed.setFontSize(ed.getFontSize() + 1);
+ is(ed.getFontSize(), size + 1, "new font size was set");
+
+ info("Check that we display unicode values for non-printable characters");
+ ed.setText("> \u202e \u2066 - \u2069 \u2066 <");
+
+ const doc = win.document.querySelector("iframe").contentWindow.document;
+ const nonPrintableCharElements = Array.from(
+ doc.querySelectorAll(".cm-non-printable-char")
+ );
+
+ Assert.deepEqual(
+ nonPrintableCharElements.map(el => el.textContent),
+ ["\\u202e", "\\u2066", "\\u2069", "\\u2066"],
+ "non printable chars are displayed as expected"
+ );
+
+ teardown(ed, win);
+}
diff --git a/devtools/client/shared/sourceeditor/test/browser_editor_cursor.js b/devtools/client/shared/sourceeditor/test/browser_editor_cursor.js
new file mode 100644
index 0000000000..c4e71424d5
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/browser_editor_cursor.js
@@ -0,0 +1,52 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+async function test() {
+ waitForExplicitFinish();
+ const { ed, win } = await setup();
+ ch(ed.getCursor(), { line: 0, ch: 0 }, "default cursor position is ok");
+ ed.setText("Hello.\nHow are you?");
+
+ ed.setCursor({ line: 1, ch: 5 });
+ ch(ed.getCursor(), { line: 1, ch: 5 }, "setCursor({ line, ch })");
+
+ ch(ed.getPosition(7), { line: 1, ch: 0 }, "getPosition(num)");
+ ch(ed.getPosition(7, 1)[0], { line: 1, ch: 0 }, "getPosition(num, num)[0]");
+ ch(ed.getPosition(7, 1)[1], { line: 0, ch: 1 }, "getPosition(num, num)[1]");
+
+ ch(ed.getOffset({ line: 1, ch: 0 }), 7, "getOffset(num)");
+ ch(
+ ed.getOffset({ line: 1, ch: 0 }, { line: 0, ch: 1 })[0],
+ 7,
+ "getOffset(num, num)[0]"
+ );
+ ch(
+ ed.getOffset({ line: 1, ch: 0 }, { line: 0, ch: 1 })[0],
+ 2,
+ "getOffset(num, num)[1]"
+ );
+
+ is(ed.getSelection(), "", "nothing is selected");
+ ed.setSelection({ line: 0, ch: 0 }, { line: 0, ch: 5 });
+ is(ed.getSelection(), "Hello", "setSelection");
+
+ ed.dropSelection();
+ is(ed.getSelection(), "", "dropSelection");
+
+ // Check that shift-click on a gutter selects the whole line (bug 919707)
+ const iframe = win.document.querySelector("iframe");
+ const gutter = iframe.contentWindow.document.querySelector(
+ ".CodeMirror-gutters"
+ );
+
+ EventUtils.sendMouseEvent(
+ { type: "mousedown", shiftKey: true },
+ gutter,
+ iframe.contentWindow
+ );
+ is(ed.getSelection(), "", "shift-click");
+
+ teardown(ed, win);
+}
diff --git a/devtools/client/shared/sourceeditor/test/browser_editor_cursor_blink.js b/devtools/client/shared/sourceeditor/test/browser_editor_cursor_blink.js
new file mode 100644
index 0000000000..5005afc0fd
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/browser_editor_cursor_blink.js
@@ -0,0 +1,73 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+// Test to make sure that the editor reacts to preference changes
+
+const CARET_BLINK_TIME = "ui.caretBlinkTime";
+
+add_task(async function () {
+ Services.prefs.clearUserPref(CARET_BLINK_TIME);
+
+ info(`Test when "${CARET_BLINK_TIME}" isn't set`);
+ let { ed, win } = await setup();
+ checkCssCustomPropertyValue(
+ ed,
+ 530,
+ "When preference isn't set, blink time is set to codeMirror default"
+ );
+ ed.destroy();
+ win.close();
+
+ info(`Test with a positive value for "${CARET_BLINK_TIME}"`);
+ let blinkTime = 200;
+ Services.prefs.setIntPref(CARET_BLINK_TIME, blinkTime);
+ ({ ed, win } = await setup());
+
+ checkCssCustomPropertyValue(
+ ed,
+ blinkTime,
+ "When preference is set, blink time reflects the pref value"
+ );
+ ed.destroy();
+ win.close();
+
+ info(`Test when "${CARET_BLINK_TIME}" is 0`);
+ blinkTime = 0;
+ Services.prefs.setIntPref(CARET_BLINK_TIME, blinkTime);
+ ({ ed, win } = await setup());
+
+ checkCssCustomPropertyValue(
+ ed,
+ blinkTime,
+ "When preference value is 0, blink time is also 0"
+ );
+ ed.destroy();
+ win.close();
+
+ info(`Test when "${CARET_BLINK_TIME}" is -1`);
+ blinkTime = -1;
+ Services.prefs.setIntPref(CARET_BLINK_TIME, blinkTime);
+ ({ ed, win } = await setup());
+
+ checkCssCustomPropertyValue(
+ ed,
+ 0,
+ "When preference value is negative, blink time is 0"
+ );
+ ed.destroy();
+ win.close();
+
+ Services.prefs.clearUserPref(CARET_BLINK_TIME);
+});
+
+function checkCssCustomPropertyValue(editor, expectedMsValue, assertionText) {
+ is(
+ editor.codeMirror
+ .getWrapperElement()
+ .style.getPropertyValue("--caret-blink-time"),
+ `${expectedMsValue}ms`,
+ assertionText
+ );
+}
diff --git a/devtools/client/shared/sourceeditor/test/browser_editor_disableSearchAddon.js b/devtools/client/shared/sourceeditor/test/browser_editor_disableSearchAddon.js
new file mode 100644
index 0000000000..8c803786e6
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/browser_editor_disableSearchAddon.js
@@ -0,0 +1,38 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+// Ensure disableSearchAddon config works as expected in the source editor.
+
+const isMacOS = Services.appinfo.OS === "Darwin";
+const L10N = new LocalizationHelper(
+ "devtools/client/locales/sourceeditor.properties"
+);
+
+const FIND_KEY = L10N.getStr("find.key");
+const REPLACE_KEY = L10N.getStr(
+ isMacOS ? "replaceAllMac.key" : "replaceAll.key"
+);
+
+add_task(async function () {
+ const { ed, win } = await setup({
+ disableSearchAddon: true,
+ });
+
+ const edDoc = ed.container.contentDocument;
+ const edWin = edDoc.defaultView;
+
+ await promiseWaitForFocus();
+ ed.focus();
+
+ synthesizeKeyShortcut(FIND_KEY, edWin);
+ const searchInput = edDoc.querySelector("input[type=search]");
+ ok(!searchInput, "the search input is not displayed");
+
+ synthesizeKeyShortcut(REPLACE_KEY, edWin);
+ const replaceInput = edDoc.querySelector(".CodeMirror-dialog > input");
+ ok(!replaceInput, "the replace input is not displayed");
+
+ teardown(ed, win);
+});
diff --git a/devtools/client/shared/sourceeditor/test/browser_editor_find_again.js b/devtools/client/shared/sourceeditor/test/browser_editor_find_again.js
new file mode 100644
index 0000000000..637c6de980
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/browser_editor_find_again.js
@@ -0,0 +1,217 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const L10N = new LocalizationHelper(
+ "devtools/client/locales/sourceeditor.properties"
+);
+
+const { OS } = Services.appinfo;
+
+// On linux, getting immediately the selection's range here fails, returning
+const FIND_KEY = L10N.getStr("find.key");
+const FINDNEXT_KEY = L10N.getStr("findNext.key");
+const FINDPREV_KEY = L10N.getStr("findPrev.key");
+// the replace's key with the appropriate modifiers based on OS
+const REPLACE_KEY =
+ OS == "Darwin"
+ ? L10N.getStr("replaceAllMac.key")
+ : L10N.getStr("replaceAll.key");
+
+// values like it's not selected – even if the selection is visible.
+// For the record, setting the selection's range immediately doesn't have
+// any effect.
+// It's like the <input> is not ready yet.
+// Therefore, we trigger the UI focus event to the <input>, waiting for the
+// response.
+// Using a timeout could also work, but that is more precise, ensuring also
+// the execution of the listeners added to the <input>'s focus.
+const dispatchAndWaitForFocus = target =>
+ new Promise(resolve => {
+ target.addEventListener(
+ "focus",
+ function () {
+ resolve(target);
+ },
+ { once: true }
+ );
+
+ target.dispatchEvent(new UIEvent("focus"));
+ });
+
+function openSearchBox(ed) {
+ const edDoc = ed.container.contentDocument;
+ const edWin = edDoc.defaultView;
+
+ let input = edDoc.querySelector("input[type=search]");
+ ok(!input, "search box closed");
+
+ // The editor needs the focus to properly receive the `synthesizeKey`
+ ed.focus();
+
+ synthesizeKeyShortcut(FINDNEXT_KEY, edWin);
+ input = edDoc.querySelector("input[type=search]");
+ ok(input, "find again command key opens the search box");
+}
+
+function testFindAgain(ed, inputLine, expectCursor, isFindPrev = false) {
+ const edDoc = ed.container.contentDocument;
+ const edWin = edDoc.defaultView;
+
+ const input = edDoc.querySelector("input[type=search]");
+ input.value = inputLine;
+
+ // Ensure the input has the focus before send the key – necessary on Linux,
+ // it seems that during the tests can be lost
+ input.focus();
+
+ if (isFindPrev) {
+ synthesizeKeyShortcut(FINDPREV_KEY, edWin);
+ } else {
+ synthesizeKeyShortcut(FINDNEXT_KEY, edWin);
+ }
+
+ ch(
+ ed.getCursor(),
+ expectCursor,
+ "find: " + inputLine + " expects cursor: " + expectCursor.toSource()
+ );
+}
+
+const testSearchBoxTextIsSelected = async function (ed) {
+ const edDoc = ed.container.contentDocument;
+ const edWin = edDoc.defaultView;
+
+ let input = edDoc.querySelector("input[type=search]");
+ ok(input, "search box is opened");
+
+ // Ensure the input has the focus before send the key – necessary on Linux,
+ // it seems that during the tests can be lost
+ input.focus();
+
+ // Close search box
+ EventUtils.synthesizeKey("VK_ESCAPE", {}, edWin);
+
+ input = edDoc.querySelector("input[type=search]");
+ ok(!input, "search box is closed");
+
+ // Re-open the search box
+ synthesizeKeyShortcut(FIND_KEY, edWin);
+
+ input = edDoc.querySelector("input[type=search]");
+ ok(input, "find command key opens the search box");
+
+ await dispatchAndWaitForFocus(input);
+
+ let { selectionStart, selectionEnd, value } = input;
+
+ ok(
+ selectionStart === 0 && selectionEnd === value.length,
+ "search box's text is selected when re-opened"
+ );
+
+ // Removing selection
+ input.setSelectionRange(0, 0);
+
+ synthesizeKeyShortcut(FIND_KEY, edWin);
+
+ ({ selectionStart, selectionEnd } = input);
+
+ ok(
+ selectionStart === 0 && selectionEnd === value.length,
+ "search box's text is selected when find key is pressed"
+ );
+
+ // Close search box
+ EventUtils.synthesizeKey("VK_ESCAPE", {}, edWin);
+};
+
+const testReplaceBoxTextIsSelected = async function (ed) {
+ const edDoc = ed.container.contentDocument;
+ const edWin = edDoc.defaultView;
+
+ let input = edDoc.querySelector(".CodeMirror-dialog > input");
+ ok(!input, "dialog box with replace is closed");
+
+ // The editor needs the focus to properly receive the `synthesizeKey`
+ ed.focus();
+
+ synthesizeKeyShortcut(REPLACE_KEY, edWin);
+
+ input = edDoc.querySelector(".CodeMirror-dialog > input");
+ ok(input, "dialog box with replace is opened");
+
+ input.value = "line 5";
+
+ // Ensure the input has the focus before send the key – necessary on Linux,
+ // it seems that during the tests can be lost
+ input.focus();
+
+ await dispatchAndWaitForFocus(input);
+
+ let { selectionStart, selectionEnd, value } = input;
+
+ ok(
+ !(selectionStart === 0 && selectionEnd === value.length),
+ "Text in dialog box is not selected"
+ );
+
+ synthesizeKeyShortcut(REPLACE_KEY, edWin);
+
+ ({ selectionStart, selectionEnd } = input);
+
+ ok(
+ selectionStart === 0 && selectionEnd === value.length,
+ "dialog box's text is selected when replace key is pressed"
+ );
+
+ // Close dialog box
+ EventUtils.synthesizeKey("VK_ESCAPE", {}, edWin);
+};
+
+add_task(async function () {
+ const { ed, win } = await setup();
+
+ ed.setText(
+ [
+ "// line 1",
+ "// line 2",
+ "// line 3",
+ "// line 4",
+ "// line 5",
+ ].join("\n")
+ );
+
+ await promiseWaitForFocus();
+
+ openSearchBox(ed);
+
+ const testVectors = [
+ // Starting here expect data needs to get updated for length changes to
+ // "textLines" above.
+ ["line", { line: 0, ch: 7 }],
+ ["line", { line: 1, ch: 8 }],
+ ["line", { line: 2, ch: 9 }],
+ ["line", { line: 3, ch: 10 }],
+ ["line", { line: 4, ch: 11 }],
+ ["ne 3", { line: 2, ch: 11 }],
+ ["line 1", { line: 0, ch: 9 }],
+ // Testing find prev
+ ["line", { line: 4, ch: 11 }, true],
+ ["line", { line: 3, ch: 10 }, true],
+ ["line", { line: 2, ch: 9 }, true],
+ ["line", { line: 1, ch: 8 }, true],
+ ["line", { line: 0, ch: 7 }, true],
+ ];
+
+ for (const v of testVectors) {
+ await testFindAgain(ed, ...v);
+ }
+
+ await testSearchBoxTextIsSelected(ed);
+
+ await testReplaceBoxTextIsSelected(ed);
+
+ teardown(ed, win);
+});
diff --git a/devtools/client/shared/sourceeditor/test/browser_editor_goto_line.js b/devtools/client/shared/sourceeditor/test/browser_editor_goto_line.js
new file mode 100644
index 0000000000..325c8c6dd5
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/browser_editor_goto_line.js
@@ -0,0 +1,91 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+function testJumpToLine(ed, inputLine, expectCursor) {
+ ed.jumpToLine();
+ const editorDoc = ed.container.contentDocument;
+ const lineInput = editorDoc.querySelector("input");
+ lineInput.value = inputLine;
+ EventUtils.synthesizeKey("VK_RETURN", {}, editorDoc.defaultView);
+ // CodeMirror lines and columns are 0-based.
+ ch(
+ ed.getCursor(),
+ expectCursor,
+ "jumpToLine " + inputLine + " expects cursor " + expectCursor.toSource()
+ );
+}
+
+async function test() {
+ waitForExplicitFinish();
+ const { ed, win } = await setup();
+ const textLines = [
+ "// line 1",
+ "// line 2",
+ "// line 3",
+ "// line 4",
+ "// line 5",
+ "",
+ ];
+ ed.setText(textLines.join("\n"));
+ await promiseWaitForFocus();
+
+ const testVectors = [
+ // Various useless inputs go to line 0, column 0 or do nothing.
+ ["", { line: 0, ch: 0 }],
+ [":", { line: 0, ch: 0 }],
+ [" ", { line: 0, ch: 0 }],
+ [" : ", { line: 0, ch: 0 }],
+ ["a:b", { line: 0, ch: 0 }],
+ ["LINE: COLUMN ", { line: 0, ch: 0 }],
+ ["-1", { line: 0, ch: 0 }],
+ [":-1", { line: 0, ch: 0 }],
+ ["-1:-1", { line: 0, ch: 0 }],
+ ["0", { line: 0, ch: 0 }],
+ [":0", { line: 0, ch: 0 }],
+ ["0:0", { line: 0, ch: 0 }],
+ // Starting here expect data needs to get updated for length changes to
+ // "textLines" above.
+ // Just jump to line
+ ["1", { line: 0, ch: 0 }],
+ // Jump to second character in line
+ ["1:2", { line: 0, ch: 1 }],
+ // Jump to last character on line
+ ["1:9", { line: 0, ch: 8 }],
+ // Jump just after last character on line (end of line)
+ ["1:10", { line: 0, ch: 9 }],
+ // Jump one character past end of line (gets clamped to end of line)
+ ["1:11", { line: 0, ch: 9 }],
+ ["2", { line: 1, ch: 0 }],
+ ["2:2", { line: 1, ch: 1 }],
+ ["2:10", { line: 1, ch: 9 }],
+ ["2:11", { line: 1, ch: 10 }],
+ ["2:12", { line: 1, ch: 10 }],
+ ["3", { line: 2, ch: 0 }],
+ ["3:2", { line: 2, ch: 1 }],
+ ["3:11", { line: 2, ch: 10 }],
+ ["3:12", { line: 2, ch: 11 }],
+ ["3:13", { line: 2, ch: 11 }],
+ ["4", { line: 3, ch: 0 }],
+ ["4:2", { line: 3, ch: 1 }],
+ ["4:12", { line: 3, ch: 11 }],
+ ["4:13", { line: 3, ch: 12 }],
+ ["4:14", { line: 3, ch: 12 }],
+ ["5", { line: 4, ch: 0 }],
+ ["5:2", { line: 4, ch: 1 }],
+ ["5:13", { line: 4, ch: 12 }],
+ ["5:14", { line: 4, ch: 13 }],
+ ["5:15", { line: 4, ch: 13 }],
+ // One line beyond last newline in editor text:
+ ["6", { line: 5, ch: 0 }],
+ ["6:2", { line: 5, ch: 0 }],
+ // Two line beyond last newline in editor text (gets clamped):
+ ["7", { line: 5, ch: 0 }],
+ ["7:2", { line: 5, ch: 0 }],
+ ];
+ testVectors.forEach(vector => {
+ testJumpToLine(ed, vector[0], vector[1]);
+ });
+ teardown(ed, win);
+}
diff --git a/devtools/client/shared/sourceeditor/test/browser_editor_history.js b/devtools/client/shared/sourceeditor/test/browser_editor_history.js
new file mode 100644
index 0000000000..2602c28236
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/browser_editor_history.js
@@ -0,0 +1,30 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+async function test() {
+ waitForExplicitFinish();
+ const { ed, win } = await setup();
+ ok(ed.isClean(), "default isClean");
+ ok(!ed.canUndo(), "default canUndo");
+ ok(!ed.canRedo(), "default canRedo");
+
+ ed.setText("Hello, World!");
+ ok(!ed.isClean(), "isClean");
+ ok(ed.canUndo(), "canUndo");
+ ok(!ed.canRedo(), "canRedo");
+
+ ed.undo();
+ ok(ed.isClean(), "isClean after undo");
+ ok(!ed.canUndo(), "canUndo after undo");
+ ok(ed.canRedo(), "canRedo after undo");
+
+ ed.setText("What's up?");
+ ed.setClean();
+ ok(ed.isClean(), "isClean after setClean");
+ ok(ed.canUndo(), "canUndo after setClean");
+ ok(!ed.canRedo(), "canRedo after setClean");
+
+ teardown(ed, win);
+}
diff --git a/devtools/client/shared/sourceeditor/test/browser_editor_markers.js b/devtools/client/shared/sourceeditor/test/browser_editor_markers.js
new file mode 100644
index 0000000000..e56ea3a425
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/browser_editor_markers.js
@@ -0,0 +1,43 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+async function test() {
+ waitForExplicitFinish();
+ const { ed, win } = await setup();
+ ok(!ed.hasMarker(0, "breakpoints", "test"), "default is ok");
+ ed.addMarker(0, "breakpoints", "test");
+ ed.addMarker(0, "breakpoints", "test2");
+ ok(ed.hasMarker(0, "breakpoints", "test"), "addMarker/1");
+ ok(ed.hasMarker(0, "breakpoints", "test2"), "addMarker/2");
+
+ ed.removeMarker(0, "breakpoints", "test");
+ ok(!ed.hasMarker(0, "breakpoints", "test"), "removeMarker/1");
+ ok(ed.hasMarker(0, "breakpoints", "test2"), "removeMarker/2");
+
+ ed.removeAllMarkers("breakpoints");
+ ok(!ed.hasMarker(0, "breakpoints", "test"), "removeAllMarkers/1");
+ ok(!ed.hasMarker(0, "breakpoints", "test2"), "removeAllMarkers/2");
+
+ ed.addMarker(0, "breakpoints", "breakpoint");
+ ed.setMarkerListeners(
+ 0,
+ "breakpoints",
+ "breakpoint",
+ {
+ click: (line, marker, param) => {
+ is(line, 0, "line is ok");
+ is(marker.className, "breakpoint", "marker is ok");
+ ok(param, "click is ok");
+
+ teardown(ed, win);
+ },
+ },
+ [true]
+ );
+
+ const env = win.document.querySelector("iframe").contentWindow;
+ const div = env.document.querySelector("div.breakpoint");
+ div.click();
+}
diff --git a/devtools/client/shared/sourceeditor/test/browser_editor_movelines.js b/devtools/client/shared/sourceeditor/test/browser_editor_movelines.js
new file mode 100644
index 0000000000..b95139b5a9
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/browser_editor_movelines.js
@@ -0,0 +1,61 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+async function test() {
+ waitForExplicitFinish();
+ const { ed, win } = await setup();
+ const simpleProg =
+ "function foo() {\n let i = 1;\n let j = 2;\n " + "return bar;\n}";
+ ed.setText(simpleProg);
+
+ // Move first line up
+ ed.setCursor({ line: 0, ch: 0 });
+ ed.moveLineUp();
+ is(ed.getText(0), "function foo() {", "getText(num)");
+ ch(ed.getCursor(), { line: 0, ch: 0 }, "getCursor");
+
+ // Move last line down
+ ed.setCursor({ line: 4, ch: 0 });
+ ed.moveLineDown();
+ is(ed.getText(4), "}", "getText(num)");
+ ch(ed.getCursor(), { line: 4, ch: 0 }, "getCursor");
+
+ // Move line 2 up
+ ed.setCursor({ line: 1, ch: 5 });
+ ed.moveLineUp();
+ is(ed.getText(0), " let i = 1;", "getText(num)");
+ is(ed.getText(1), "function foo() {", "getText(num)");
+ ch(ed.getCursor(), { line: 0, ch: 5 }, "getCursor");
+
+ // Undo previous move by moving line 1 down
+ ed.moveLineDown();
+ is(ed.getText(0), "function foo() {", "getText(num)");
+ is(ed.getText(1), " let i = 1;", "getText(num)");
+ ch(ed.getCursor(), { line: 1, ch: 5 }, "getCursor");
+
+ // Move line 2 and 3 up
+ ed.setSelection({ line: 1, ch: 0 }, { line: 2, ch: 0 });
+ ed.moveLineUp();
+ is(ed.getText(0), " let i = 1;", "getText(num)");
+ is(ed.getText(1), " let j = 2;", "getText(num)");
+ is(ed.getText(2), "function foo() {", "getText(num)");
+ ch(ed.getCursor("start"), { line: 0, ch: 0 }, "getCursor(string)");
+ ch(ed.getCursor("end"), { line: 1, ch: 0 }, "getCursor(string)");
+
+ // Move line 1 to 3 down twice
+ ed.dropSelection();
+ ed.setSelection({ line: 0, ch: 7 }, { line: 2, ch: 5 });
+ ed.moveLineDown();
+ ed.moveLineDown();
+ is(ed.getText(0), " return bar;", "getText(num)");
+ is(ed.getText(1), "}", "getText(num)");
+ is(ed.getText(2), " let i = 1;", "getText(num)");
+ is(ed.getText(3), " let j = 2;", "getText(num)");
+ is(ed.getText(4), "function foo() {", "getText(num)");
+ ch(ed.getCursor("start"), { line: 2, ch: 7 }, "getCursor(string)");
+ ch(ed.getCursor("end"), { line: 4, ch: 5 }, "getCursor(string)");
+
+ teardown(ed, win);
+}
diff --git a/devtools/client/shared/sourceeditor/test/browser_editor_prefs.js b/devtools/client/shared/sourceeditor/test/browser_editor_prefs.js
new file mode 100644
index 0000000000..2063796f76
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/browser_editor_prefs.js
@@ -0,0 +1,139 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+// Test to make sure that the editor reacts to preference changes
+
+const TAB_SIZE = "devtools.editor.tabsize";
+const ENABLE_CODE_FOLDING = "devtools.editor.enableCodeFolding";
+const EXPAND_TAB = "devtools.editor.expandtab";
+const KEYMAP = "devtools.editor.keymap";
+const AUTO_CLOSE = "devtools.editor.autoclosebrackets";
+const AUTOCOMPLETE = "devtools.editor.autocomplete";
+const DETECT_INDENT = "devtools.editor.detectindentation";
+
+async function test() {
+ waitForExplicitFinish();
+ const { ed, win } = await setup();
+ Assert.deepEqual(
+ ed.getOption("gutters"),
+ ["CodeMirror-linenumbers", "breakpoints", "CodeMirror-foldgutter"],
+ "gutters is correct"
+ );
+
+ ed.setText("Checking preferences.");
+
+ info("Turning prefs off");
+
+ ed.setOption("autocomplete", true);
+
+ Services.prefs.setIntPref(TAB_SIZE, 2);
+ Services.prefs.setBoolPref(ENABLE_CODE_FOLDING, false);
+ Services.prefs.setBoolPref(EXPAND_TAB, false);
+ Services.prefs.setCharPref(KEYMAP, "default");
+ Services.prefs.setBoolPref(AUTO_CLOSE, false);
+ Services.prefs.setBoolPref(AUTOCOMPLETE, false);
+ Services.prefs.setBoolPref(DETECT_INDENT, false);
+
+ Assert.deepEqual(
+ ed.getOption("gutters"),
+ ["CodeMirror-linenumbers", "breakpoints"],
+ "gutters is correct"
+ );
+
+ is(ed.getOption("tabSize"), 2, "tabSize is correct");
+ is(ed.getOption("indentUnit"), 2, "indentUnit is correct");
+ is(ed.getOption("foldGutter"), false, "foldGutter is correct");
+ is(
+ ed.getOption("enableCodeFolding"),
+ undefined,
+ "enableCodeFolding is correct"
+ );
+ is(ed.getOption("indentWithTabs"), true, "indentWithTabs is correct");
+ is(ed.getOption("keyMap"), "default", "keyMap is correct");
+ is(ed.getOption("autoCloseBrackets"), false, "autoCloseBrackets is correct");
+ is(ed.getOption("autocomplete"), true, "autocomplete is correct");
+ ok(!ed.isAutocompletionEnabled(), "Autocompletion is not enabled");
+
+ info("Turning prefs on");
+
+ Services.prefs.setIntPref(TAB_SIZE, 4);
+ Services.prefs.setBoolPref(ENABLE_CODE_FOLDING, true);
+ Services.prefs.setBoolPref(EXPAND_TAB, true);
+ Services.prefs.setCharPref(KEYMAP, "sublime");
+ Services.prefs.setBoolPref(AUTO_CLOSE, true);
+ Services.prefs.setBoolPref(AUTOCOMPLETE, true);
+
+ Assert.deepEqual(
+ ed.getOption("gutters"),
+ ["CodeMirror-linenumbers", "breakpoints", "CodeMirror-foldgutter"],
+ "gutters is correct"
+ );
+
+ is(ed.getOption("tabSize"), 4, "tabSize is correct");
+ is(ed.getOption("indentUnit"), 4, "indentUnit is correct");
+ is(ed.getOption("foldGutter"), true, "foldGutter is correct");
+ is(
+ ed.getOption("enableCodeFolding"),
+ undefined,
+ "enableCodeFolding is correct"
+ );
+ is(ed.getOption("indentWithTabs"), false, "indentWithTabs is correct");
+ is(
+ ed.getOption("autoCloseBrackets"),
+ "()[]{}''\"\"``",
+ "autoCloseBrackets is correct"
+ );
+ is(ed.getOption("autocomplete"), true, "autocomplete is correct");
+ ok(ed.isAutocompletionEnabled(), "Autocompletion is enabled");
+
+ // Since the keyMap files are lazily loaded, this can take some time. We need to wait
+ // until the option has the expected value.
+ info("Wait for the keyMap option to be updated");
+ await waitUntil(() => ed.getOption("keyMap") === "sublime");
+ is(ed.getOption("keyMap"), "sublime", "keyMap is correct");
+
+ info("Forcing foldGutter off using enableCodeFolding");
+ ed.setOption("enableCodeFolding", false);
+
+ is(ed.getOption("foldGutter"), false, "foldGutter is correct");
+ is(ed.getOption("enableCodeFolding"), false, "enableCodeFolding is correct");
+ Assert.deepEqual(
+ ed.getOption("gutters"),
+ ["CodeMirror-linenumbers", "breakpoints"],
+ "gutters is correct"
+ );
+
+ info("Forcing foldGutter on using enableCodeFolding");
+ ed.setOption("enableCodeFolding", true);
+
+ is(ed.getOption("foldGutter"), true, "foldGutter is correct");
+ is(ed.getOption("enableCodeFolding"), true, "enableCodeFolding is correct");
+ Assert.deepEqual(
+ ed.getOption("gutters"),
+ ["CodeMirror-linenumbers", "breakpoints", "CodeMirror-foldgutter"],
+ "gutters is correct"
+ );
+
+ info("Checking indentation detection");
+
+ Services.prefs.setBoolPref(DETECT_INDENT, true);
+
+ ed.setText("Detecting\n\tTabs");
+ is(ed.getOption("indentWithTabs"), true, "indentWithTabs is correct");
+ is(ed.getOption("indentUnit"), 4, "indentUnit is correct");
+
+ ed.setText("body {\n color:red;\n a:b;\n}");
+ is(ed.getOption("indentWithTabs"), false, "indentWithTabs is correct");
+ is(ed.getOption("indentUnit"), 2, "indentUnit is correct");
+
+ Services.prefs.clearUserPref(TAB_SIZE);
+ Services.prefs.clearUserPref(EXPAND_TAB);
+ Services.prefs.clearUserPref(KEYMAP);
+ Services.prefs.clearUserPref(AUTO_CLOSE);
+ Services.prefs.clearUserPref(AUTOCOMPLETE);
+ Services.prefs.clearUserPref(DETECT_INDENT);
+
+ teardown(ed, win);
+}
diff --git a/devtools/client/shared/sourceeditor/test/browser_vimemacs.js b/devtools/client/shared/sourceeditor/test/browser_vimemacs.js
new file mode 100644
index 0000000000..cda5899b70
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/browser_vimemacs.js
@@ -0,0 +1,13 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+"use strict";
+
+const URI =
+ "chrome://mochitests/content/browser/devtools/client" +
+ "/shared/sourceeditor/test/codemirror/vimemacs.html";
+
+add_task(async function test() {
+ requestLongerTimeout(4);
+ await runCodeMirrorTest(URI);
+});
diff --git a/devtools/client/shared/sourceeditor/test/cm_mode_ruby.js b/devtools/client/shared/sourceeditor/test/cm_mode_ruby.js
new file mode 100644
index 0000000000..991dede14a
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/cm_mode_ruby.js
@@ -0,0 +1,285 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: http://codemirror.net/LICENSE
+
+(function (mod) {
+ if (typeof exports == "object" && typeof module == "object") // CommonJS
+ mod(require("resource://devtools/client/shared/lib/codemirror.js"));
+ else if (typeof define == "function" && define.amd) // AMD
+ define(["../../lib/codemirror"], mod);
+ else // Plain browser env
+ mod(CodeMirror);
+})(function (CodeMirror) {
+ "use strict";
+
+ CodeMirror.defineMode("ruby", function (config) {
+ function wordObj(words) {
+ var o = {};
+ for (var i = 0, e = words.length; i < e; ++i) o[words[i]] = true;
+ return o;
+ }
+ var keywords = wordObj([
+ "alias", "and", "BEGIN", "begin", "break", "case", "class", "def", "defined?", "do", "else",
+ "elsif", "END", "end", "ensure", "false", "for", "if", "in", "module", "next", "not", "or",
+ "redo", "rescue", "retry", "return", "self", "super", "then", "true", "undef", "unless",
+ "until", "when", "while", "yield", "nil", "raise", "throw", "catch", "fail", "loop", "callcc",
+ "caller", "lambda", "proc", "public", "protected", "private", "require", "load",
+ "require_relative", "extend", "autoload", "__END__", "__FILE__", "__LINE__", "__dir__"
+ ]);
+ var indentWords = wordObj(["def", "class", "case", "for", "while", "module", "then",
+ "catch", "loop", "proc", "begin"]);
+ var dedentWords = wordObj(["end", "until"]);
+ var matching = {"[": "]", "{": "}", "(": ")"};
+ var curPunc;
+
+ function chain(newtok, stream, state) {
+ state.tokenize.push(newtok);
+ return newtok(stream, state);
+ }
+
+ function tokenBase(stream, state) {
+ curPunc = null;
+ if (stream.sol() && stream.match("=begin") && stream.eol()) {
+ state.tokenize.push(readBlockComment);
+ return "comment";
+ }
+ if (stream.eatSpace()) return null;
+ var ch = stream.next(), m;
+ if (ch == "`" || ch == "'" || ch == '"') {
+ return chain(readQuoted(ch, "string", ch == '"' || ch == "`"), stream, state);
+ } else if (ch == "/") {
+ var currentIndex = stream.current().length;
+ if (stream.skipTo("/")) {
+ var search_till = stream.current().length;
+ stream.backUp(stream.current().length - currentIndex);
+ var balance = 0; // balance brackets
+ while (stream.current().length < search_till) {
+ var chchr = stream.next();
+ if (chchr == "(") balance += 1;
+ else if (chchr == ")") balance -= 1;
+ if (balance < 0) break;
+ }
+ stream.backUp(stream.current().length - currentIndex);
+ if (balance == 0)
+ return chain(readQuoted(ch, "string-2", true), stream, state);
+ }
+ return "operator";
+ } else if (ch == "%") {
+ var style = "string", embed = true;
+ if (stream.eat("s")) style = "atom";
+ else if (stream.eat(/[WQ]/)) style = "string";
+ else if (stream.eat(/[r]/)) style = "string-2";
+ else if (stream.eat(/[wxq]/)) { style = "string"; embed = false; }
+ var delim = stream.eat(/[^\w\s=]/);
+ if (!delim) return "operator";
+ if (matching.propertyIsEnumerable(delim)) delim = matching[delim];
+ return chain(readQuoted(delim, style, embed, true), stream, state);
+ } else if (ch == "#") {
+ stream.skipToEnd();
+ return "comment";
+ } else if (ch == "<" && (m = stream.match(/^<-?[\`\"\']?([a-zA-Z_?]\w*)[\`\"\']?(?:;|$)/))) {
+ return chain(readHereDoc(m[1]), stream, state);
+ } else if (ch == "0") {
+ if (stream.eat("x")) stream.eatWhile(/[\da-fA-F]/);
+ else if (stream.eat("b")) stream.eatWhile(/[01]/);
+ else stream.eatWhile(/[0-7]/);
+ return "number";
+ } else if (/\d/.test(ch)) {
+ stream.match(/^[\d_]*(?:\.[\d_]+)?(?:[eE][+\-]?[\d_]+)?/);
+ return "number";
+ } else if (ch == "?") {
+ while (stream.match(/^\\[CM]-/)) {}
+ if (stream.eat("\\")) stream.eatWhile(/\w/);
+ else stream.next();
+ return "string";
+ } else if (ch == ":") {
+ if (stream.eat("'")) return chain(readQuoted("'", "atom", false), stream, state);
+ if (stream.eat('"')) return chain(readQuoted('"', "atom", true), stream, state);
+
+ // :> :>> :< :<< are valid symbols
+ if (stream.eat(/[\<\>]/)) {
+ stream.eat(/[\<\>]/);
+ return "atom";
+ }
+
+ // :+ :- :/ :* :| :& :! are valid symbols
+ if (stream.eat(/[\+\-\*\/\&\|\:\!]/)) {
+ return "atom";
+ }
+
+ // Symbols can't start by a digit
+ if (stream.eat(/[a-zA-Z$@_\xa1-\uffff]/)) {
+ stream.eatWhile(/[\w$\xa1-\uffff]/);
+ // Only one ? ! = is allowed and only as the last character
+ stream.eat(/[\?\!\=]/);
+ return "atom";
+ }
+ return "operator";
+ } else if (ch == "@" && stream.match(/^@?[a-zA-Z_\xa1-\uffff]/)) {
+ stream.eat("@");
+ stream.eatWhile(/[\w\xa1-\uffff]/);
+ return "variable-2";
+ } else if (ch == "$") {
+ if (stream.eat(/[a-zA-Z_]/)) {
+ stream.eatWhile(/[\w]/);
+ } else if (stream.eat(/\d/)) {
+ stream.eat(/\d/);
+ } else {
+ stream.next(); // Must be a special global like $: or $!
+ }
+ return "variable-3";
+ } else if (/[a-zA-Z_\xa1-\uffff]/.test(ch)) {
+ stream.eatWhile(/[\w\xa1-\uffff]/);
+ stream.eat(/[\?\!]/);
+ if (stream.eat(":")) return "atom";
+ return "ident";
+ } else if (ch == "|" && (state.varList || state.lastTok == "{" || state.lastTok == "do")) {
+ curPunc = "|";
+ return null;
+ } else if (/[\(\)\[\]{}\\;]/.test(ch)) {
+ curPunc = ch;
+ return null;
+ } else if (ch == "-" && stream.eat(">")) {
+ return "arrow";
+ } else if (/[=+\-\/*:\.^%<>~|]/.test(ch)) {
+ var more = stream.eatWhile(/[=+\-\/*:\.^%<>~|]/);
+ if (ch == "." && !more) curPunc = ".";
+ return "operator";
+ } else {
+ return null;
+ }
+ }
+
+ function tokenBaseUntilBrace(depth) {
+ if (!depth) depth = 1;
+ return function (stream, state) {
+ if (stream.peek() == "}") {
+ if (depth == 1) {
+ state.tokenize.pop();
+ return state.tokenize[state.tokenize.length - 1](stream, state);
+ } else {
+ state.tokenize[state.tokenize.length - 1] = tokenBaseUntilBrace(depth - 1);
+ }
+ } else if (stream.peek() == "{") {
+ state.tokenize[state.tokenize.length - 1] = tokenBaseUntilBrace(depth + 1);
+ }
+ return tokenBase(stream, state);
+ };
+ }
+ function tokenBaseOnce() {
+ var alreadyCalled = false;
+ return function (stream, state) {
+ if (alreadyCalled) {
+ state.tokenize.pop();
+ return state.tokenize[state.tokenize.length - 1](stream, state);
+ }
+ alreadyCalled = true;
+ return tokenBase(stream, state);
+ };
+ }
+ function readQuoted(quote, style, embed, unescaped) {
+ return function (stream, state) {
+ var escaped = false, ch;
+
+ if (state.context.type === "read-quoted-paused") {
+ state.context = state.context.prev;
+ stream.eat("}");
+ }
+
+ while ((ch = stream.next()) != null) {
+ if (ch == quote && (unescaped || !escaped)) {
+ state.tokenize.pop();
+ break;
+ }
+ if (embed && ch == "#" && !escaped) {
+ if (stream.eat("{")) {
+ if (quote == "}") {
+ state.context = {prev: state.context, type: "read-quoted-paused"};
+ }
+ state.tokenize.push(tokenBaseUntilBrace());
+ break;
+ } else if (/[@\$]/.test(stream.peek())) {
+ state.tokenize.push(tokenBaseOnce());
+ break;
+ }
+ }
+ escaped = !escaped && ch == "\\";
+ }
+ return style;
+ };
+ }
+ function readHereDoc(phrase) {
+ return function (stream, state) {
+ if (stream.match(phrase)) state.tokenize.pop();
+ else stream.skipToEnd();
+ return "string";
+ };
+ }
+ function readBlockComment(stream, state) {
+ if (stream.sol() && stream.match("=end") && stream.eol())
+ state.tokenize.pop();
+ stream.skipToEnd();
+ return "comment";
+ }
+
+ return {
+ startState: function () {
+ return {tokenize: [tokenBase],
+ indented: 0,
+ context: {type: "top", indented: -config.indentUnit},
+ continuedLine: false,
+ lastTok: null,
+ varList: false};
+ },
+
+ token: function (stream, state) {
+ if (stream.sol()) state.indented = stream.indentation();
+ var style = state.tokenize[state.tokenize.length - 1](stream, state), kwtype;
+ var thisTok = curPunc;
+ if (style == "ident") {
+ var word = stream.current();
+ style = state.lastTok == "." ? "property"
+ : keywords.propertyIsEnumerable(stream.current()) ? "keyword"
+ : /^[A-Z]/.test(word) ? "tag"
+ : (state.lastTok == "def" || state.lastTok == "class" || state.varList) ? "def"
+ : "variable";
+ if (style == "keyword") {
+ thisTok = word;
+ if (indentWords.propertyIsEnumerable(word)) kwtype = "indent";
+ else if (dedentWords.propertyIsEnumerable(word)) kwtype = "dedent";
+ else if ((word == "if" || word == "unless") && stream.column() == stream.indentation())
+ kwtype = "indent";
+ else if (word == "do" && state.context.indented < state.indented)
+ kwtype = "indent";
+ }
+ }
+ if (curPunc || (style && style != "comment")) state.lastTok = thisTok;
+ if (curPunc == "|") state.varList = !state.varList;
+
+ if (kwtype == "indent" || /[\(\[\{]/.test(curPunc))
+ state.context = {prev: state.context, type: curPunc || style, indented: state.indented};
+ else if ((kwtype == "dedent" || /[\)\]\}]/.test(curPunc)) && state.context.prev)
+ state.context = state.context.prev;
+
+ if (stream.eol())
+ state.continuedLine = (curPunc == "\\" || style == "operator");
+ return style;
+ },
+
+ indent: function (state, textAfter) {
+ if (state.tokenize[state.tokenize.length - 1] != tokenBase) return 0;
+ var firstChar = textAfter && textAfter.charAt(0);
+ var ct = state.context;
+ var closing = ct.type == matching[firstChar] ||
+ ct.type == "keyword" && /^(?:end|until|else|elsif|when|rescue)\b/.test(textAfter);
+ return ct.indented + (closing ? 0 : config.indentUnit) +
+ (state.continuedLine ? config.indentUnit : 0);
+ },
+
+ electricChars: "}de", // enD and rescuE
+ lineComment: "#"
+ };
+ });
+
+ CodeMirror.defineMIME("text/x-ruby", "ruby");
+
+});
diff --git a/devtools/client/shared/sourceeditor/test/cm_script_injection_test.js b/devtools/client/shared/sourceeditor/test/cm_script_injection_test.js
new file mode 100644
index 0000000000..85d0794682
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/cm_script_injection_test.js
@@ -0,0 +1,10 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/* global editor */
+
+"use strict";
+
+window.addEventListener("editorReady", function () {
+ editor.setText("Script successfully injected!");
+});
diff --git a/devtools/client/shared/sourceeditor/test/codemirror/codemirror.html b/devtools/client/shared/sourceeditor/test/codemirror/codemirror.html
new file mode 100644
index 0000000000..950747c490
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/codemirror/codemirror.html
@@ -0,0 +1,213 @@
+<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8">
+ <title>CodeMirror: Basic Tests</title>
+ <link rel="stylesheet" href="chrome://devtools/content/shared/sourceeditor/codemirror/lib/codemirror.css">
+ <link rel="stylesheet" href="cm_mode_test.css">
+ <!--<link rel="stylesheet" href="../doc/docs.css">-->
+
+ <script src="chrome://devtools/content/shared/sourceeditor/codemirror/codemirror.bundle.js"></script>
+ <script src="chrome://devtools/content/shared/sourceeditor/codemirror/keymap/emacs.js"></script>
+ <script src="chrome://devtools/content/shared/sourceeditor/codemirror/keymap/sublime.js"></script>
+ <script src="chrome://devtools/content/shared/sourceeditor/codemirror/keymap/vim.js"></script>
+
+ <style type="text/css">
+ .ok {color: #090;}
+ .fail {color: #e00;}
+ .error {color: #c90;}
+ .done {font-weight: bold;}
+ #progress {
+ background: #45d;
+ color: white;
+ text-shadow: 0 0 1px #45d, 0 0 2px #45d, 0 0 3px #45d;
+ font-weight: bold;
+ white-space: pre;
+ }
+ #testground {
+ visibility: hidden;
+ }
+ #testground.offscreen {
+ visibility: visible;
+ position: absolute;
+ left: -10000px;
+ top: -10000px;
+ }
+ .CodeMirror { border: 1px solid black; }
+ </style>
+ </head>
+ <body>
+ <h1>CodeMirror: Basic Tests</h1>
+
+ <p>A limited set of programmatic sanity tests for CodeMirror.</p>
+
+ <div style="border: 1px solid black; padding: 1px; max-width: 700px;">
+ <div style="width: 0px;" id=progress><div style="padding: 3px;">Ran <span id="progress_ran">0</span><span id="progress_total"> of 0</span> tests</div></div>
+ </div>
+ <p id=status>Please enable JavaScript...</p>
+ <div id=output></div>
+
+ <div id=testground></div>
+
+ <script src="driver.js"></script>
+ <script src="test.js"></script>
+ <script src="comment_test.js"></script>
+ <script src="doc_test.js"></script>
+ <script src="driver.js"></script>
+ <script src="emacs_test.js"></script>
+ <script src="mode_test.js"></script>
+ <script src="mode/javascript/test.js"></script>
+ <script src="multi_test.js"></script>
+ <script src="search_test.js"></script>
+
+ <!-- VIM and Emacs mode tests are in vimemacs.html
+ <script src="cm_sublime_test.js"></script>
+ <script src="cm_vim_test.js"></script>
+ <script src="cm_emacs_test.js"></script>
+ -->
+
+ <!-- These modes/addons are not used by Editor
+ <script src="doc_test.js"></script>
+ <script src="../mode/css/css.js"></script>
+ <script src="../mode/css/test.js"></script>
+ <script src="../mode/css/scss_test.js"></script>
+ <script src="../mode/xml/xml.js"></script>
+ <script src="../mode/htmlmixed/htmlmixed.js"></script>
+ <script src="../mode/ruby/ruby.js"></script>
+ <script src="../mode/haml/haml.js"></script>
+ <script src="../mode/haml/test.js"></script>
+ <script src="../mode/markdown/markdown.js"></script>
+ <script src="../mode/markdown/test.js"></script>
+ <script src="../mode/gfm/gfm.js"></script>
+ <script src="../mode/gfm/test.js"></script>
+ <script src="../mode/stex/stex.js"></script>
+ <script src="../mode/stex/test.js"></script>
+ <script src="../mode/xquery/xquery.js"></script>
+ <script src="../mode/xquery/test.js"></script>
+ <script src="../addon/mode/multiplex_test.js"></script>-->
+
+ <script>
+ window.onload = runHarness;
+ CodeMirror.on(window, 'hashchange', runHarness);
+
+ function esc(str) {
+ return str.replace(/[<&]/, function(ch) { return ch == "<" ? "&lt;" : "&amp;"; });
+ }
+
+ var output = document.getElementById("output"),
+ progress = document.getElementById("progress"),
+ progressRan = document.getElementById("progress_ran").childNodes[0],
+ progressTotal = document.getElementById("progress_total").childNodes[0];
+
+ var count = 0,
+ failed = 0,
+ skipped = 0,
+ bad = "",
+ running = false, // Flag that states tests are running
+ quit = false, // Flag to quit tests ASAP
+ verbose = false, // Adds message for *every* test to output
+ phantom = false;
+
+ function runHarness(){
+ if (running) {
+ quit = true;
+ setStatus("Restarting tests...", '', true);
+ setTimeout(function(){runHarness();}, 500);
+ return;
+ }
+ filters = [];
+ verbose = false;
+ if (window.location.hash.substr(1)){
+ var strings = window.location.hash.substr(1).split(",");
+ while (strings.length) {
+ var s = strings.shift();
+ if (s === "verbose")
+ verbose = true;
+ else
+ filters.push(parseTestFilter(decodeURIComponent(s)));
+ }
+ }
+ quit = false;
+ running = true;
+ setStatus("Loading tests...");
+ count = 0;
+ failed = 0;
+ skipped = 0;
+ bad = "";
+ totalTests = countTests();
+ progressTotal.nodeValue = " of " + totalTests;
+ progressRan.nodeValue = count;
+ output.innerHTML = '';
+ document.getElementById("testground").innerHTML = "<form>" +
+ "<textarea id=\"code\" name=\"code\"></textarea>" +
+ "<input type=submit value=ok name=submit>" +
+ "</form>";
+ runTests(displayTest);
+ }
+
+ function setStatus(message, className, force){
+ if (quit && !force) return;
+ if (!message) throw("must provide message");
+ var status = document.getElementById("status").childNodes[0];
+ status.nodeValue = message;
+ status.parentNode.className = className;
+ }
+ function addOutput(name, className, code){
+ var newOutput = document.createElement("dl");
+ var newTitle = document.createElement("dt");
+ newTitle.className = className;
+ newTitle.appendChild(document.createTextNode(name));
+ newOutput.appendChild(newTitle);
+ var newMessage = document.createElement("dd");
+ newMessage.innerHTML = code;
+ newOutput.appendChild(newTitle);
+ newOutput.appendChild(newMessage);
+ output.appendChild(newOutput);
+ }
+ function displayTest(type, name, customMessage) {
+ var message = "???";
+ if (type != "done" && type != "skipped") ++count;
+ progress.style.width = (count * (progress.parentNode.clientWidth - 2) / totalTests) + "px";
+ progressRan.nodeValue = count;
+ if (type == "ok") {
+ message = "Test '" + name + "' succeeded";
+ if (!verbose) customMessage = false;
+ } else if (type == "skipped") {
+ message = "Test '" + name + "' skipped";
+ ++skipped;
+ if (!verbose) customMessage = false;
+ } else if (type == "expected") {
+ message = "Test '" + name + "' failed as expected";
+ if (!verbose) customMessage = false;
+ } else if (type == "error" || type == "fail") {
+ ++failed;
+ message = "Test '" + name + "' failed";
+ } else if (type == "done") {
+ if (failed) {
+ type += " fail";
+ message = failed + " failure" + (failed > 1 ? "s" : "");
+ } else if (count < totalTests) {
+ failed = totalTests - count;
+ type += " fail";
+ message = failed + " failure" + (failed > 1 ? "s" : "");
+ } else {
+ type += " ok";
+ message = "All passed";
+ if (skipped) {
+ message += " (" + skipped + " skipped)";
+ }
+ }
+ progressTotal.nodeValue = '';
+ customMessage = true; // Hack to avoid adding to output
+ }
+ if (window.mozilla_setStatus)
+ mozilla_setStatus(message, type, customMessage);
+ if (verbose && !customMessage) customMessage = message;
+ setStatus(message, type);
+ if (customMessage && customMessage.length > 0) {
+ addOutput(name, type, customMessage);
+ }
+ }
+ </script>
+ </body>
+</html>
diff --git a/devtools/client/shared/sourceeditor/test/codemirror/comment_test.js b/devtools/client/shared/sourceeditor/test/codemirror/comment_test.js
new file mode 100644
index 0000000000..c6b9fe8109
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/codemirror/comment_test.js
@@ -0,0 +1,114 @@
+namespace = "comment_";
+
+(function() {
+ function test(name, mode, run, before, after) {
+ return testCM(name, function(cm) {
+ run(cm);
+ eq(cm.getValue(), after);
+ }, {value: before, mode: mode});
+ }
+
+ var simpleProg = "function foo() {\n return bar;\n}";
+ var inlineBlock = "foo(/* bar */ true);";
+ var inlineBlocks = "foo(/* bar */ true, /* baz */ false);";
+ var multiLineInlineBlock = ["above();", "foo(/* bar */ true);", "below();"];
+
+ test("block", "javascript", function(cm) {
+ cm.blockComment(Pos(0, 3), Pos(3, 0), {blockCommentLead: " *"});
+ }, simpleProg + "\n", "/* function foo() {\n * return bar;\n * }\n */");
+
+ test("blockToggle", "javascript", function(cm) {
+ cm.blockComment(Pos(0, 3), Pos(2, 0), {blockCommentLead: " *"});
+ cm.uncomment(Pos(0, 3), Pos(2, 0), {blockCommentLead: " *"});
+ }, simpleProg, simpleProg);
+
+ test("blockToggle2", "javascript", function(cm) {
+ cm.setCursor({line: 0, ch: 7 /* inside the block comment */});
+ cm.execCommand("toggleComment");
+ }, inlineBlock, "foo(bar true);");
+
+ // This test should work but currently fails.
+ // test("blockToggle3", "javascript", function(cm) {
+ // cm.setCursor({line: 0, ch: 7 /* inside the first block comment */});
+ // cm.execCommand("toggleComment");
+ // }, inlineBlocks, "foo(bar true, /* baz */ false);");
+
+ test("line", "javascript", function(cm) {
+ cm.lineComment(Pos(1, 1), Pos(1, 1));
+ }, simpleProg, "function foo() {\n// return bar;\n}");
+
+ test("lineToggle", "javascript", function(cm) {
+ cm.lineComment(Pos(0, 0), Pos(2, 1));
+ cm.uncomment(Pos(0, 0), Pos(2, 1));
+ }, simpleProg, simpleProg);
+
+ test("fallbackToBlock", "css", function(cm) {
+ cm.lineComment(Pos(0, 0), Pos(2, 1));
+ }, "html {\n border: none;\n}", "/* html {\n border: none;\n} */");
+
+ test("fallbackToLine", "ruby", function(cm) {
+ cm.blockComment(Pos(0, 0), Pos(1));
+ }, "def blah()\n return hah\n", "# def blah()\n# return hah\n");
+
+ test("ignoreExternalBlockComments", "javascript", function(cm) {
+ cm.execCommand("toggleComment");
+ }, inlineBlocks, "// " + inlineBlocks);
+
+ test("ignoreExternalBlockComments2", "javascript", function(cm) {
+ cm.setCursor({line: 0, ch: null /* eol */});
+ cm.execCommand("toggleComment");
+ }, inlineBlocks, "// " + inlineBlocks);
+
+ test("ignoreExternalBlockCommentsMultiLineAbove", "javascript", function(cm) {
+ cm.setSelection({line: 0, ch: 0}, {line: 1, ch: 1});
+ cm.execCommand("toggleComment");
+ }, multiLineInlineBlock.join("\n"), ["// " + multiLineInlineBlock[0],
+ "// " + multiLineInlineBlock[1],
+ multiLineInlineBlock[2]].join("\n"));
+
+ test("ignoreExternalBlockCommentsMultiLineBelow", "javascript", function(cm) {
+ cm.setSelection({line: 1, ch: 13 /* after end of block comment */}, {line: 2, ch: 1});
+ cm.execCommand("toggleComment");
+ }, multiLineInlineBlock.join("\n"), [multiLineInlineBlock[0],
+ "// " + multiLineInlineBlock[1],
+ "// " + multiLineInlineBlock[2]].join("\n"));
+
+ test("commentRange", "javascript", function(cm) {
+ cm.blockComment(Pos(1, 2), Pos(1, 13), {fullLines: false});
+ }, simpleProg, "function foo() {\n /*return bar;*/\n}");
+
+ test("indented", "javascript", function(cm) {
+ cm.lineComment(Pos(1, 0), Pos(2), {indent: true});
+ }, simpleProg, "function foo() {\n// return bar;\n// }");
+
+ test("singleEmptyLine", "javascript", function(cm) {
+ cm.setCursor(1);
+ cm.execCommand("toggleComment");
+ }, "a;\n\nb;", "a;\n// \nb;");
+
+ test("dontMessWithStrings", "javascript", function(cm) {
+ cm.execCommand("toggleComment");
+ }, "console.log(\"/*string*/\");", "// console.log(\"/*string*/\");");
+
+ test("dontMessWithStrings2", "javascript", function(cm) {
+ cm.execCommand("toggleComment");
+ }, "console.log(\"// string\");", "// console.log(\"// string\");");
+
+ test("dontMessWithStrings3", "javascript", function(cm) {
+ cm.execCommand("toggleComment");
+ }, "// console.log(\"// string\");", "console.log(\"// string\");");
+
+ test("includeLastLine", "javascript", function(cm) {
+ cm.execCommand("selectAll")
+ cm.execCommand("toggleComment")
+ }, "// foo\n// bar\nbaz", "// // foo\n// // bar\n// baz")
+
+ test("uncommentWithTrailingBlockEnd", "xml", function(cm) {
+ cm.execCommand("toggleComment")
+ }, "<!-- foo --> -->", "foo -->")
+
+ test("dontCommentInComment", "xml", function(cm) {
+ cm.setCursor(1, 0)
+ cm.execCommand("toggleComment")
+ }, "<!-- foo\nbar -->", "<!-- foo\nbar -->")
+})();
diff --git a/devtools/client/shared/sourceeditor/test/codemirror/doc_test.js b/devtools/client/shared/sourceeditor/test/codemirror/doc_test.js
new file mode 100644
index 0000000000..3af20ff98d
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/codemirror/doc_test.js
@@ -0,0 +1,371 @@
+(function() {
+ // A minilanguage for instantiating linked CodeMirror instances and Docs
+ function instantiateSpec(spec, place, opts) {
+ var names = {}, pos = 0, l = spec.length, editors = [];
+ while (spec) {
+ var m = spec.match(/^(\w+)(\*?)(?:='([^\']*)'|<(~?)(\w+)(?:\/(\d+)-(\d+))?)\s*/);
+ var name = m[1], isDoc = m[2], cur;
+ if (m[3]) {
+ cur = isDoc ? CodeMirror.Doc(m[3]) : CodeMirror(place, clone(opts, {value: m[3]}));
+ } else {
+ var other = m[5];
+ if (!names.hasOwnProperty(other)) {
+ names[other] = editors.length;
+ editors.push(CodeMirror(place, opts));
+ }
+ var doc = editors[names[other]].linkedDoc({
+ sharedHist: !m[4],
+ from: m[6] ? Number(m[6]) : null,
+ to: m[7] ? Number(m[7]) : null
+ });
+ cur = isDoc ? doc : CodeMirror(place, clone(opts, {value: doc}));
+ }
+ names[name] = editors.length;
+ editors.push(cur);
+ spec = spec.slice(m[0].length);
+ }
+ return editors;
+ }
+
+ function clone(obj, props) {
+ if (!obj) return;
+ clone.prototype = obj;
+ var inst = new clone();
+ if (props) for (var n in props) if (props.hasOwnProperty(n))
+ inst[n] = props[n];
+ return inst;
+ }
+
+ function eqAll(val) {
+ var end = arguments.length, msg = null;
+ if (typeof arguments[end-1] == "string")
+ msg = arguments[--end];
+ if (i == end) throw new Error("No editors provided to eqAll");
+ for (var i = 1; i < end; ++i)
+ eq(arguments[i].getValue(), val, msg)
+ }
+
+ function testDoc(name, spec, run, opts, expectFail) {
+ if (!opts) opts = {};
+
+ return test("doc_" + name, function() {
+ var place = document.getElementById("testground");
+ var editors = instantiateSpec(spec, place, opts);
+ var successful = false;
+
+ try {
+ run.apply(null, editors);
+ successful = true;
+ } finally {
+ if (!successful || verbose) {
+ place.style.visibility = "visible";
+ } else {
+ for (var i = 0; i < editors.length; ++i)
+ if (editors[i] instanceof CodeMirror)
+ place.removeChild(editors[i].getWrapperElement());
+ }
+ }
+ }, expectFail);
+ }
+
+ var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent);
+
+ function testBasic(a, b) {
+ eqAll("x", a, b);
+ a.setValue("hey");
+ eqAll("hey", a, b);
+ b.setValue("wow");
+ eqAll("wow", a, b);
+ a.replaceRange("u\nv\nw", Pos(0, 3));
+ b.replaceRange("i", Pos(0, 4));
+ b.replaceRange("j", Pos(2, 1));
+ eqAll("wowui\nv\nwj", a, b);
+ }
+
+ testDoc("basic", "A='x' B<A", testBasic);
+ testDoc("basicSeparate", "A='x' B<~A", testBasic);
+
+ testDoc("sharedHist", "A='ab\ncd\nef' B<A", function(a, b) {
+ a.replaceRange("x", Pos(0));
+ b.replaceRange("y", Pos(1));
+ a.replaceRange("z", Pos(2));
+ eqAll("abx\ncdy\nefz", a, b);
+ a.undo();
+ a.undo();
+ eqAll("abx\ncd\nef", a, b);
+ a.redo();
+ eqAll("abx\ncdy\nef", a, b);
+ b.redo();
+ eqAll("abx\ncdy\nefz", a, b);
+ a.undo(); b.undo(); a.undo(); a.undo();
+ eqAll("ab\ncd\nef", a, b);
+ }, null, ie_lt8);
+
+ testDoc("undoIntact", "A='ab\ncd\nef' B<~A", function(a, b) {
+ a.replaceRange("x", Pos(0));
+ b.replaceRange("y", Pos(1));
+ a.replaceRange("z", Pos(2));
+ a.replaceRange("q", Pos(0));
+ eqAll("abxq\ncdy\nefz", a, b);
+ a.undo();
+ a.undo();
+ eqAll("abx\ncdy\nef", a, b);
+ b.undo();
+ eqAll("abx\ncd\nef", a, b);
+ a.redo();
+ eqAll("abx\ncd\nefz", a, b);
+ a.redo();
+ eqAll("abxq\ncd\nefz", a, b);
+ a.undo(); a.undo(); a.undo(); a.undo();
+ eqAll("ab\ncd\nef", a, b);
+ b.redo();
+ eqAll("ab\ncdy\nef", a, b);
+ });
+
+ testDoc("undoConflict", "A='ab\ncd\nef' B<~A", function(a, b) {
+ a.replaceRange("x", Pos(0));
+ a.replaceRange("z", Pos(2));
+ // This should clear the first undo event in a, but not the second
+ b.replaceRange("y", Pos(0));
+ a.undo(); a.undo();
+ eqAll("abxy\ncd\nef", a, b);
+ a.replaceRange("u", Pos(2));
+ a.replaceRange("v", Pos(0));
+ // This should clear both events in a
+ b.replaceRange("w", Pos(0));
+ a.undo(); a.undo();
+ eqAll("abxyvw\ncd\nefu", a, b);
+ });
+
+ testDoc("doubleRebase", "A='ab\ncd\nef\ng' B<~A C<B", function(a, b, c) {
+ c.replaceRange("u", Pos(3));
+ a.replaceRange("", Pos(0, 0), Pos(1, 0));
+ c.undo();
+ eqAll("cd\nef\ng", a, b, c);
+ });
+
+ testDoc("undoUpdate", "A='ab\ncd\nef' B<~A", function(a, b) {
+ a.replaceRange("x", Pos(2));
+ b.replaceRange("u\nv\nw\n", Pos(0, 0));
+ a.undo();
+ eqAll("u\nv\nw\nab\ncd\nef", a, b);
+ a.redo();
+ eqAll("u\nv\nw\nab\ncd\nefx", a, b);
+ a.undo();
+ eqAll("u\nv\nw\nab\ncd\nef", a, b);
+ b.undo();
+ a.redo();
+ eqAll("ab\ncd\nefx", a, b);
+ a.undo();
+ eqAll("ab\ncd\nef", a, b);
+ });
+
+ testDoc("undoKeepRanges", "A='abcdefg' B<A", function(a, b) {
+ var m = a.markText(Pos(0, 1), Pos(0, 3), {className: "foo"});
+ b.replaceRange("x", Pos(0, 0));
+ eqCharPos(m.find().from, Pos(0, 2));
+ b.replaceRange("yzzy", Pos(0, 1), Pos(0));
+ eq(m.find(), null);
+ b.undo();
+ eqCharPos(m.find().from, Pos(0, 2));
+ b.undo();
+ eqCharPos(m.find().from, Pos(0, 1));
+ });
+
+ testDoc("longChain", "A='uv' B<A C<B D<C", function(a, b, c, d) {
+ a.replaceSelection("X");
+ eqAll("Xuv", a, b, c, d);
+ d.replaceRange("Y", Pos(0));
+ eqAll("XuvY", a, b, c, d);
+ });
+
+ testDoc("broadCast", "B<A C<A D<A E<A", function(a, b, c, d, e) {
+ b.setValue("uu");
+ eqAll("uu", a, b, c, d, e);
+ a.replaceRange("v", Pos(0, 1));
+ eqAll("uvu", a, b, c, d, e);
+ });
+
+ // A and B share a history, C and D share a separate one
+ testDoc("islands", "A='x\ny\nz' B<A C<~A D<C", function(a, b, c, d) {
+ a.replaceRange("u", Pos(0));
+ d.replaceRange("v", Pos(2));
+ b.undo();
+ eqAll("x\ny\nzv", a, b, c, d);
+ c.undo();
+ eqAll("x\ny\nz", a, b, c, d);
+ a.redo();
+ eqAll("xu\ny\nz", a, b, c, d);
+ d.redo();
+ eqAll("xu\ny\nzv", a, b, c, d);
+ });
+
+ testDoc("unlink", "B<A C<A D<B", function(a, b, c, d) {
+ a.setValue("hi");
+ b.unlinkDoc(a);
+ d.setValue("aye");
+ eqAll("hi", a, c);
+ eqAll("aye", b, d);
+ a.setValue("oo");
+ eqAll("oo", a, c);
+ eqAll("aye", b, d);
+ });
+
+ testDoc("bareDoc", "A*='foo' B*<A C<B", function(a, b, c) {
+ is(a instanceof CodeMirror.Doc);
+ is(b instanceof CodeMirror.Doc);
+ is(c instanceof CodeMirror);
+ eqAll("foo", a, b, c);
+ a.replaceRange("hey", Pos(0, 0), Pos(0));
+ c.replaceRange("!", Pos(0));
+ eqAll("hey!", a, b, c);
+ b.unlinkDoc(a);
+ b.setValue("x");
+ eqAll("x", b, c);
+ eqAll("hey!", a);
+ });
+
+ testDoc("swapDoc", "A='a' B*='b' C<A", function(a, b, c) {
+ var d = a.swapDoc(b);
+ d.setValue("x");
+ eqAll("x", c, d);
+ eqAll("b", a, b);
+ });
+
+ testDoc("docKeepsScroll", "A='x' B*='y'", function(a, b) {
+ addDoc(a, 200, 200);
+ a.scrollIntoView(Pos(199, 200));
+ var c = a.swapDoc(b);
+ a.swapDoc(c);
+ var pos = a.getScrollInfo();
+ is(pos.left > 0, "not at left");
+ is(pos.top > 0, "not at top");
+ });
+
+ testDoc("copyDoc", "A='u'", function(a) {
+ var copy = a.getDoc().copy(true);
+ a.setValue("foo");
+ copy.setValue("bar");
+ var old = a.swapDoc(copy);
+ eq(a.getValue(), "bar");
+ a.undo();
+ eq(a.getValue(), "u");
+ a.swapDoc(old);
+ eq(a.getValue(), "foo");
+ eq(old.historySize().undo, 1);
+ eq(old.copy(false).historySize().undo, 0);
+ });
+
+ testDoc("docKeepsMode", "A='1+1'", function(a) {
+ var other = CodeMirror.Doc("hi", "text/x-markdown");
+ a.setOption("mode", "text/javascript");
+ var old = a.swapDoc(other);
+ eq(a.getOption("mode"), "text/x-markdown");
+ eq(a.getMode().name, "markdown");
+ a.swapDoc(old);
+ eq(a.getOption("mode"), "text/javascript");
+ eq(a.getMode().name, "javascript");
+ });
+
+ testDoc("subview", "A='1\n2\n3\n4\n5' B<~A/1-3", function(a, b) {
+ eq(b.getValue(), "2\n3");
+ eq(b.firstLine(), 1);
+ b.setCursor(Pos(4));
+ eqCharPos(b.getCursor(), Pos(2, 1));
+ a.replaceRange("-1\n0\n", Pos(0, 0));
+ eq(b.firstLine(), 3);
+ eqCharPos(b.getCursor(), Pos(4, 1));
+ a.undo();
+ eqCharPos(b.getCursor(), Pos(2, 1));
+ b.replaceRange("oyoy\n", Pos(2, 0));
+ eq(a.getValue(), "1\n2\noyoy\n3\n4\n5");
+ b.undo();
+ eq(a.getValue(), "1\n2\n3\n4\n5");
+ });
+
+ testDoc("subviewEditOnBoundary", "A='11\n22\n33\n44\n55' B<~A/1-4", function(a, b) {
+ a.replaceRange("x\nyy\nz", Pos(0, 1), Pos(2, 1));
+ eq(b.firstLine(), 2);
+ eq(b.lineCount(), 2);
+ eq(b.getValue(), "z3\n44");
+ a.replaceRange("q\nrr\ns", Pos(3, 1), Pos(4, 1));
+ eq(b.firstLine(), 2);
+ eq(b.getValue(), "z3\n4q");
+ eq(a.getValue(), "1x\nyy\nz3\n4q\nrr\ns5");
+ a.execCommand("selectAll");
+ a.replaceSelection("!");
+ eqAll("!", a, b);
+ });
+
+
+ testDoc("sharedMarker", "A='ab\ncd\nef\ngh' B<A C<~A/1-2", function(a, b, c) {
+ var mark = b.markText(Pos(0, 1), Pos(3, 1),
+ {className: "cm-searching", shared: true});
+ var found = a.findMarksAt(Pos(0, 2));
+ eq(found.length, 1);
+ eq(found[0], mark);
+ eq(c.findMarksAt(Pos(1, 1)).length, 1);
+ eqCharPos(mark.find().from, Pos(0, 1));
+ eqCharPos(mark.find().to, Pos(3, 1));
+ b.replaceRange("x\ny\n", Pos(0, 0));
+ eqCharPos(mark.find().from, Pos(2, 1));
+ eqCharPos(mark.find().to, Pos(5, 1));
+ var cleared = 0;
+ CodeMirror.on(mark, "clear", function() {++cleared;});
+ b.operation(function(){mark.clear();});
+ eq(a.findMarksAt(Pos(3, 1)).length, 0);
+ eq(b.findMarksAt(Pos(3, 1)).length, 0);
+ eq(c.findMarksAt(Pos(3, 1)).length, 0);
+ eq(mark.find(), null);
+ eq(cleared, 1);
+ });
+
+ testDoc("sharedMarkerCopy", "A='abcde'", function(a) {
+ var shared = a.markText(Pos(0, 1), Pos(0, 3), {shared: true});
+ var b = a.linkedDoc();
+ var found = b.findMarksAt(Pos(0, 2));
+ eq(found.length, 1);
+ eq(found[0], shared);
+ shared.clear();
+ eq(b.findMarksAt(Pos(0, 2)), 0);
+ });
+
+ testDoc("sharedMarkerDetach", "A='abcde' B<A C<B", function(a, b, c) {
+ var shared = a.markText(Pos(0, 1), Pos(0, 3), {shared: true});
+ a.unlinkDoc(b);
+ var inB = b.findMarksAt(Pos(0, 2));
+ eq(inB.length, 1);
+ is(inB[0] != shared);
+ var inC = c.findMarksAt(Pos(0, 2));
+ eq(inC.length, 1);
+ is(inC[0] != shared);
+ inC[0].clear();
+ is(shared.find());
+ });
+
+ testDoc("sharedBookmark", "A='ab\ncd\nef\ngh' B<A C<~A/1-2", function(a, b, c) {
+ var mark = b.setBookmark(Pos(1, 1), {shared: true});
+ var found = a.findMarksAt(Pos(1, 1));
+ eq(found.length, 1);
+ eq(found[0], mark);
+ eq(c.findMarksAt(Pos(1, 1)).length, 1);
+ eqCharPos(mark.find(), Pos(1, 1));
+ b.replaceRange("x\ny\n", Pos(0, 0));
+ eqCharPos(mark.find(), Pos(3, 1));
+ var cleared = 0;
+ CodeMirror.on(mark, "clear", function() {++cleared;});
+ b.operation(function() {mark.clear();});
+ eq(a.findMarks(Pos(0, 0), Pos(5)).length, 0);
+ eq(b.findMarks(Pos(0, 0), Pos(5)).length, 0);
+ eq(c.findMarks(Pos(0, 0), Pos(5)).length, 0);
+ eq(mark.find(), null);
+ eq(cleared, 1);
+ });
+
+ testDoc("undoInSubview", "A='line 0\nline 1\nline 2\nline 3\nline 4' B<A/1-4", function(a, b) {
+ b.replaceRange("x", Pos(2, 0));
+ a.undo();
+ eq(a.getValue(), "line 0\nline 1\nline 2\nline 3\nline 4");
+ eq(b.getValue(), "line 1\nline 2\nline 3");
+ });
+})();
diff --git a/devtools/client/shared/sourceeditor/test/codemirror/driver.js b/devtools/client/shared/sourceeditor/test/codemirror/driver.js
new file mode 100644
index 0000000000..8789f73be9
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/codemirror/driver.js
@@ -0,0 +1,142 @@
+var tests = [], filters = [], allNames = [];
+
+function Failure(why) {this.message = why;}
+Failure.prototype.toString = function() { return this.message; };
+
+function indexOf(collection, elt) {
+ if (collection.indexOf) return collection.indexOf(elt);
+ for (var i = 0, e = collection.length; i < e; ++i)
+ if (collection[i] == elt) return i;
+ return -1;
+}
+
+function test(name, run, expectedFail) {
+ // Force unique names
+ var originalName = name;
+ var i = 2; // Second function would be NAME_2
+ while (indexOf(allNames, name) !== -1){
+ name = originalName + "_" + i;
+ i++;
+ }
+ allNames.push(name);
+ // Add test
+ tests.push({name: name, func: run, expectedFail: expectedFail});
+ return name;
+}
+var namespace = "";
+function testCM(name, run, opts, expectedFail) {
+ return test(namespace + name, function() {
+ var place = document.getElementById("testground"), cm = window.cm = CodeMirror(place, opts);
+ var successful = false;
+ try {
+ run(cm);
+ successful = true;
+ } finally {
+ if (!successful || verbose) {
+ place.style.visibility = "visible";
+ } else {
+ place.removeChild(cm.getWrapperElement());
+ }
+ }
+ }, expectedFail);
+}
+
+function runTests(callback) {
+ var totalTime = 0;
+ function step(i) {
+ for (;;) {
+ if (i === tests.length) {
+ running = false;
+ return callback("done");
+ }
+ var test = tests[i], skip = false;
+ if (filters.length) {
+ skip = true;
+ for (var j = 0; j < filters.length; j++)
+ if (test.name.match(filters[j])) skip = false;
+ }
+ if (skip) {
+ callback("skipped", test.name, message);
+ i++;
+ } else {
+ break;
+ }
+ }
+ var expFail = test.expectedFail, startTime = +new Date, threw = false;
+ try {
+ var message = test.func();
+ } catch(e) {
+ threw = true;
+ if (expFail) callback("expected", test.name);
+ else if (e instanceof Failure) callback("fail", test.name, e.message);
+ else {
+ var pos = /(?:\bat |@).*?([^\/:]+):(\d+)/.exec(e.stack);
+ if (pos) console["log"](e.stack);
+ callback("error", test.name, e.toString() + (pos ? " (" + pos[1] + ":" + pos[2] + ")" : ""));
+ }
+ }
+ if (!threw) {
+ if (expFail) callback("fail", test.name, message || "expected failure, but passed");
+ else callback("ok", test.name, message);
+ }
+ if (!quit) { // Run next test
+ var delay = 0;
+ totalTime += (+new Date) - startTime;
+ if (totalTime > 500){
+ totalTime = 0;
+ delay = 50;
+ }
+ setTimeout(function(){step(i + 1);}, delay);
+ } else { // Quit tests
+ running = false;
+ return null;
+ }
+ }
+ step(0);
+}
+
+function label(str, msg) {
+ if (msg) return str + " (" + msg + ")";
+ return str;
+}
+function eq(a, b, msg) {
+ if (a != b) throw new Failure(label(a + " != " + b, msg));
+}
+function near(a, b, margin, msg) {
+ if (Math.abs(a - b) > margin)
+ throw new Failure(label(a + " is not close to " + b + " (" + margin + ")", msg));
+}
+function eqCharPos(a, b, msg) {
+ function str(p) { return "{line:" + p.line + ",ch:" + p.ch + ",sticky:" + p.sticky + "}"; }
+ if (a == b) return;
+ if (a == null) throw new Failure(label("comparing null to " + str(b), msg));
+ if (b == null) throw new Failure(label("comparing " + str(a) + " to null", msg));
+ if (a.line != b.line || a.ch != b.ch) throw new Failure(label(str(a) + " != " + str(b), msg));
+}
+function eqCursorPos(a, b, msg) {
+ eqCharPos(a, b, msg);
+ if (a) eq(a.sticky, b.sticky, msg ? msg + ' (sticky)' : 'sticky');
+}
+function is(a, msg) {
+ if (!a) throw new Failure(label("assertion failed", msg));
+}
+
+function countTests() {
+ if (!filters.length) return tests.length;
+ var sum = 0;
+ for (var i = 0; i < tests.length; ++i) {
+ var name = tests[i].name;
+ for (var j = 0; j < filters.length; j++) {
+ if (name.match(filters[j])) {
+ ++sum;
+ break;
+ }
+ }
+ }
+ return sum;
+}
+
+function parseTestFilter(s) {
+ if (/_\*$/.test(s)) return new RegExp("^" + s.slice(0, s.length - 2), "i");
+ else return new RegExp(s, "i");
+}
diff --git a/devtools/client/shared/sourceeditor/test/codemirror/emacs_test.js b/devtools/client/shared/sourceeditor/test/codemirror/emacs_test.js
new file mode 100644
index 0000000000..412dba4b42
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/codemirror/emacs_test.js
@@ -0,0 +1,149 @@
+(function() {
+ "use strict";
+
+ var Pos = CodeMirror.Pos;
+ namespace = "emacs_";
+
+ var eventCache = {};
+ function fakeEvent(keyName) {
+ var event = eventCache[key];
+ if (event) return event;
+
+ var ctrl, shift, alt;
+ var key = keyName.replace(/\w+-/g, function(type) {
+ if (type == "Ctrl-") ctrl = true;
+ else if (type == "Alt-") alt = true;
+ else if (type == "Shift-") shift = true;
+ return "";
+ });
+ var code;
+ for (var c in CodeMirror.keyNames)
+ if (CodeMirror.keyNames[c] == key) { code = c; break; }
+ if (code == null) throw new Error("Unknown key: " + key);
+
+ return eventCache[keyName] = {
+ type: "keydown", keyCode: code, ctrlKey: ctrl, shiftKey: shift, altKey: alt,
+ preventDefault: function(){}, stopPropagation: function(){}
+ };
+ }
+
+ function sim(name, start /*, actions... */) {
+ var keys = Array.prototype.slice.call(arguments, 2);
+ testCM(name, function(cm) {
+ for (var i = 0; i < keys.length; ++i) {
+ var cur = keys[i];
+ if (cur instanceof Pos) cm.setCursor(cur);
+ else if (cur.call) cur(cm);
+ else cm.triggerOnKeyDown(fakeEvent(cur));
+ }
+ }, {keyMap: "emacs", value: start, mode: "javascript"});
+ }
+
+ function at(line, ch, sticky) { return function(cm) { eqCursorPos(cm.getCursor(), Pos(line, ch, sticky)); }; }
+ function txt(str) { return function(cm) { eq(cm.getValue(), str); }; }
+
+ sim("motionHSimple", "abc", "Ctrl-F", "Ctrl-F", "Ctrl-B", at(0, 1, "after"));
+ sim("motionHMulti", "abcde",
+ "Ctrl-4", "Ctrl-F", at(0, 4, "before"), "Ctrl--", "Ctrl-2", "Ctrl-F", at(0, 2, "after"),
+ "Ctrl-5", "Ctrl-B", at(0, 0, "after"));
+
+ sim("motionHWord", "abc. def ghi",
+ "Alt-F", at(0, 3, "before"), "Alt-F", at(0, 8, "before"),
+ "Ctrl-B", "Alt-B", at(0, 5, "after"), "Alt-B", at(0, 0, "after"));
+ sim("motionHWordMulti", "abc. def ghi ",
+ "Ctrl-3", "Alt-F", at(0, 12, "before"), "Ctrl-2", "Alt-B", at(0, 5, "after"),
+ "Ctrl--", "Alt-B", at(0, 8, "before"));
+
+ sim("motionVSimple", "a\nb\nc\n", "Ctrl-N", "Ctrl-N", "Ctrl-P", at(1, 0, "after"));
+ sim("motionVMulti", "a\nb\nc\nd\ne\n",
+ "Ctrl-2", "Ctrl-N", at(2, 0, "after"), "Ctrl-F", "Ctrl--", "Ctrl-N", at(1, 1, "before"),
+ "Ctrl--", "Ctrl-3", "Ctrl-P", at(4, 1, "before"));
+
+ sim("killYank", "abc\ndef\nghi",
+ "Ctrl-F", "Ctrl-Space", "Ctrl-N", "Ctrl-N", "Ctrl-W", "Ctrl-E", "Ctrl-Y",
+ txt("ahibc\ndef\ng"));
+ sim("killRing", "abcdef",
+ "Ctrl-Space", "Ctrl-F", "Ctrl-W", "Ctrl-Space", "Ctrl-F", "Ctrl-W",
+ "Ctrl-Y", "Alt-Y",
+ txt("acdef"));
+ sim("copyYank", "abcd",
+ "Ctrl-Space", "Ctrl-E", "Alt-W", "Ctrl-Y",
+ txt("abcdabcd"));
+
+ sim("killLineSimple", "foo\nbar", "Ctrl-F", "Ctrl-K", txt("f\nbar"));
+ sim("killLineEmptyLine", "foo\n \nbar", "Ctrl-N", "Ctrl-K", txt("foo\nbar"));
+ sim("killLineMulti", "foo\nbar\nbaz",
+ "Ctrl-F", "Ctrl-F", "Ctrl-K", "Ctrl-K", "Ctrl-K", "Ctrl-A", "Ctrl-Y",
+ txt("o\nbarfo\nbaz"));
+
+ sim("moveByParagraph", "abc\ndef\n\n\nhij\nklm\n\n",
+ "Ctrl-F", "Ctrl-Down", at(2, 0), "Ctrl-Down", at(6, 0),
+ "Ctrl-N", "Ctrl-Up", at(3, 0), "Ctrl-Up", at(0, 0),
+ Pos(1, 2), "Ctrl-Down", at(2, 0), Pos(4, 2), "Ctrl-Up", at(3, 0));
+ sim("moveByParagraphMulti", "abc\n\ndef\n\nhij\n\nklm",
+ "Ctrl-U", "2", "Ctrl-Down", at(3, 0),
+ "Shift-Alt-.", "Ctrl-3", "Ctrl-Up", at(1, 0));
+
+ sim("moveBySentence", "sentence one! sentence\ntwo\n\nparagraph two",
+ "Alt-E", at(0, 13), "Alt-E", at(1, 3), "Ctrl-F", "Alt-A", at(0, 13));
+
+ sim("moveByExpr", "function foo(a, b) {}",
+ "Ctrl-Alt-F", at(0, 8), "Ctrl-Alt-F", at(0, 12), "Ctrl-Alt-F", at(0, 18),
+ "Ctrl-Alt-B", at(0, 12), "Ctrl-Alt-B", at(0, 9));
+ sim("moveByExprMulti", "foo bar baz bug",
+ "Ctrl-2", "Ctrl-Alt-F", at(0, 7),
+ "Ctrl--", "Ctrl-Alt-F", at(0, 4),
+ "Ctrl--", "Ctrl-2", "Ctrl-Alt-B", at(0, 11));
+ sim("delExpr", "var x = [\n a,\n b\n c\n];",
+ Pos(0, 8), "Ctrl-Alt-K", txt("var x = ;"), "Ctrl-/",
+ Pos(4, 1), "Ctrl-Alt-Backspace", txt("var x = ;"));
+ sim("delExprMulti", "foo bar baz",
+ "Ctrl-2", "Ctrl-Alt-K", txt(" baz"),
+ "Ctrl-/", "Ctrl-E", "Ctrl-2", "Ctrl-Alt-Backspace", txt("foo "));
+
+ sim("justOneSpace", "hi bye ",
+ Pos(0, 4), "Alt-Space", txt("hi bye "),
+ Pos(0, 4), "Alt-Space", txt("hi b ye "),
+ "Ctrl-A", "Alt-Space", "Ctrl-E", "Alt-Space", txt(" hi b ye "));
+
+ sim("openLine", "foo bar", "Alt-F", "Ctrl-O", txt("foo\n bar"))
+
+ sim("transposeChar", "abcd\ne",
+ "Ctrl-F", "Ctrl-T", "Ctrl-T", txt("bcad\ne"), at(0, 3),
+ "Ctrl-F", "Ctrl-T", "Ctrl-T", "Ctrl-T", txt("bcda\ne"), at(0, 4),
+ "Ctrl-F", "Ctrl-T", txt("bcde\na"), at(1, 1));
+
+ sim("manipWordCase", "foo BAR bAZ",
+ "Alt-C", "Alt-L", "Alt-U", txt("Foo bar BAZ"),
+ "Ctrl-A", "Alt-U", "Alt-L", "Alt-C", txt("FOO bar Baz"));
+ sim("manipWordCaseMulti", "foo Bar bAz",
+ "Ctrl-2", "Alt-U", txt("FOO BAR bAz"),
+ "Ctrl-A", "Ctrl-3", "Alt-C", txt("Foo Bar Baz"));
+
+ sim("upExpr", "foo {\n bar[];\n baz(blah);\n}",
+ Pos(2, 7), "Ctrl-Alt-U", at(2, 5), "Ctrl-Alt-U", at(0, 4));
+ sim("transposeExpr", "do foo[bar] dah",
+ Pos(0, 6), "Ctrl-Alt-T", txt("do [bar]foo dah"));
+
+ sim("clearMark", "abcde", Pos(0, 2), "Ctrl-Space", "Ctrl-F", "Ctrl-F",
+ "Ctrl-G", "Ctrl-W", txt("abcde"));
+
+ sim("delRegion", "abcde", "Ctrl-Space", "Ctrl-F", "Ctrl-F", "Delete", txt("cde"));
+ sim("backspaceRegion", "abcde", "Ctrl-Space", "Ctrl-F", "Ctrl-F", "Backspace", txt("cde"));
+
+ sim("backspaceDoesntAddToRing", "foobar", "Ctrl-F", "Ctrl-F", "Ctrl-F", "Ctrl-K", "Backspace", "Backspace", "Ctrl-Y", txt("fbar"));
+
+ testCM("save", function(cm) {
+ var saved = false;
+ CodeMirror.commands.save = function(cm) { saved = cm.getValue(); };
+ cm.triggerOnKeyDown(fakeEvent("Ctrl-X"));
+ cm.triggerOnKeyDown(fakeEvent("Ctrl-S"));
+ is(saved, "hi");
+ }, {value: "hi", keyMap: "emacs"});
+
+ testCM("gotoInvalidLineFloat", function(cm) {
+ cm.openDialog = function(_, cb) { cb("2.2"); };
+ cm.triggerOnKeyDown(fakeEvent("Alt-G"));
+ cm.triggerOnKeyDown(fakeEvent("G"));
+ }, {value: "1\n2\n3\n4", keyMap: "emacs"});
+})();
diff --git a/devtools/client/shared/sourceeditor/test/codemirror/mode/javascript/test.js b/devtools/client/shared/sourceeditor/test/codemirror/mode/javascript/test.js
new file mode 100644
index 0000000000..327eac76b9
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/codemirror/mode/javascript/test.js
@@ -0,0 +1,513 @@
+// CodeMirror, copyright (c) by Marijn Haverbeke and others
+// Distributed under an MIT license: https://codemirror.net/LICENSE
+
+(function() {
+ var mode = CodeMirror.getMode({indentUnit: 2}, "javascript");
+ function MT(name) { test.mode(name, mode, Array.prototype.slice.call(arguments, 1)); }
+
+ MT("locals",
+ "[keyword function] [def foo]([def a], [def b]) { [keyword var] [def c] [operator =] [number 10]; [keyword return] [variable-2 a] [operator +] [variable-2 c] [operator +] [variable d]; }");
+
+ MT("comma-and-binop",
+ "[keyword function](){ [keyword var] [def x] [operator =] [number 1] [operator +] [number 2], [def y]; }");
+
+ MT("destructuring",
+ "([keyword function]([def a], [[[def b], [def c] ]]) {",
+ " [keyword let] {[def d], [property foo]: [def c][operator =][number 10], [def x]} [operator =] [variable foo]([variable-2 a]);",
+ " [[[variable-2 c], [variable y] ]] [operator =] [variable-2 c];",
+ "})();");
+
+ MT("destructure_trailing_comma",
+ "[keyword let] {[def a], [def b],} [operator =] [variable foo];",
+ "[keyword let] [def c];"); // Parser still in good state?
+
+ MT("class_body",
+ "[keyword class] [def Foo] {",
+ " [property constructor]() {}",
+ " [property sayName]() {",
+ " [keyword return] [string-2 `foo${][variable foo][string-2 }oo`];",
+ " }",
+ "}");
+
+ MT("class",
+ "[keyword class] [def Point] [keyword extends] [variable SuperThing] {",
+ " [keyword get] [property prop]() { [keyword return] [number 24]; }",
+ " [property constructor]([def x], [def y]) {",
+ " [keyword super]([string 'something']);",
+ " [keyword this].[property x] [operator =] [variable-2 x];",
+ " }",
+ "}");
+
+ MT("anonymous_class_expression",
+ "[keyword const] [def Adder] [operator =] [keyword class] [keyword extends] [variable Arithmetic] {",
+ " [property add]([def a], [def b]) {}",
+ "};");
+
+ MT("named_class_expression",
+ "[keyword const] [def Subber] [operator =] [keyword class] [def Subtract] {",
+ " [property sub]([def a], [def b]) {}",
+ "};");
+
+ MT("class_async_method",
+ "[keyword class] [def Foo] {",
+ " [property sayName1]() {}",
+ " [keyword async] [property sayName2]() {}",
+ "}");
+
+ MT("import",
+ "[keyword function] [def foo]() {",
+ " [keyword import] [def $] [keyword from] [string 'jquery'];",
+ " [keyword import] { [def encrypt], [def decrypt] } [keyword from] [string 'crypto'];",
+ "}");
+
+ MT("import_trailing_comma",
+ "[keyword import] {[def foo], [def bar],} [keyword from] [string 'baz']")
+
+ MT("import_dynamic",
+ "[keyword import]([string 'baz']).[property then]")
+
+ MT("import_dynamic",
+ "[keyword const] [def t] [operator =] [keyword import]([string 'baz']).[property then]")
+
+ MT("const",
+ "[keyword function] [def f]() {",
+ " [keyword const] [[ [def a], [def b] ]] [operator =] [[ [number 1], [number 2] ]];",
+ "}");
+
+ MT("for/of",
+ "[keyword for]([keyword let] [def of] [keyword of] [variable something]) {}");
+
+ MT("for await",
+ "[keyword for] [keyword await]([keyword let] [def of] [keyword of] [variable something]) {}");
+
+ MT("generator",
+ "[keyword function*] [def repeat]([def n]) {",
+ " [keyword for]([keyword var] [def i] [operator =] [number 0]; [variable-2 i] [operator <] [variable-2 n]; [operator ++][variable-2 i])",
+ " [keyword yield] [variable-2 i];",
+ "}");
+
+ MT("let_scoping",
+ "[keyword function] [def scoped]([def n]) {",
+ " { [keyword var] [def i]; } [variable-2 i];",
+ " { [keyword let] [def j]; [variable-2 j]; } [variable j];",
+ " [keyword if] ([atom true]) { [keyword const] [def k]; [variable-2 k]; } [variable k];",
+ "}");
+
+ MT("switch_scoping",
+ "[keyword switch] ([variable x]) {",
+ " [keyword default]:",
+ " [keyword let] [def j];",
+ " [keyword return] [variable-2 j]",
+ "}",
+ "[variable j];")
+
+ MT("leaving_scope",
+ "[keyword function] [def a]() {",
+ " {",
+ " [keyword const] [def x] [operator =] [number 1]",
+ " [keyword if] ([atom true]) {",
+ " [keyword let] [def y] [operator =] [number 2]",
+ " [keyword var] [def z] [operator =] [number 3]",
+ " [variable console].[property log]([variable-2 x], [variable-2 y], [variable-2 z])",
+ " }",
+ " [variable console].[property log]([variable-2 x], [variable y], [variable-2 z])",
+ " }",
+ " [variable console].[property log]([variable x], [variable y], [variable-2 z])",
+ "}")
+
+ MT("quotedStringAddition",
+ "[keyword let] [def f] [operator =] [variable a] [operator +] [string 'fatarrow'] [operator +] [variable c];");
+
+ MT("quotedFatArrow",
+ "[keyword let] [def f] [operator =] [variable a] [operator +] [string '=>'] [operator +] [variable c];");
+
+ MT("fatArrow",
+ "[variable array].[property filter]([def a] [operator =>] [variable-2 a] [operator +] [number 1]);",
+ "[variable a];", // No longer in scope
+ "[keyword let] [def f] [operator =] ([[ [def a], [def b] ]], [def c]) [operator =>] [variable-2 a] [operator +] [variable-2 c];",
+ "[variable c];");
+
+ MT("fatArrow_stringDefault",
+ "([def a], [def b] [operator =] [string 'x\\'y']) [operator =>] [variable-2 a] [operator +] [variable-2 b]")
+
+ MT("spread",
+ "[keyword function] [def f]([def a], [meta ...][def b]) {",
+ " [variable something]([variable-2 a], [meta ...][variable-2 b]);",
+ "}");
+
+ MT("quasi",
+ "[variable re][string-2 `fofdlakj${][variable x] [operator +] ([variable re][string-2 `foo`]) [operator +] [number 1][string-2 }fdsa`] [operator +] [number 2]");
+
+ MT("quasi_no_function",
+ "[variable x] [operator =] [string-2 `fofdlakj${][variable x] [operator +] [string-2 `foo`] [operator +] [number 1][string-2 }fdsa`] [operator +] [number 2]");
+
+ MT("indent_statement",
+ "[keyword var] [def x] [operator =] [number 10]",
+ "[variable x] [operator +=] [variable y] [operator +]",
+ " [atom Infinity]",
+ "[keyword debugger];");
+
+ MT("indent_if",
+ "[keyword if] ([number 1])",
+ " [keyword break];",
+ "[keyword else] [keyword if] ([number 2])",
+ " [keyword continue];",
+ "[keyword else]",
+ " [number 10];",
+ "[keyword if] ([number 1]) {",
+ " [keyword break];",
+ "} [keyword else] [keyword if] ([number 2]) {",
+ " [keyword continue];",
+ "} [keyword else] {",
+ " [number 10];",
+ "}");
+
+ MT("indent_for",
+ "[keyword for] ([keyword var] [def i] [operator =] [number 0];",
+ " [variable i] [operator <] [number 100];",
+ " [variable i][operator ++])",
+ " [variable doSomething]([variable i]);",
+ "[keyword debugger];");
+
+ MT("indent_c_style",
+ "[keyword function] [def foo]()",
+ "{",
+ " [keyword debugger];",
+ "}");
+
+ MT("indent_else",
+ "[keyword for] (;;)",
+ " [keyword if] ([variable foo])",
+ " [keyword if] ([variable bar])",
+ " [number 1];",
+ " [keyword else]",
+ " [number 2];",
+ " [keyword else]",
+ " [number 3];");
+
+ MT("indent_funarg",
+ "[variable foo]([number 10000],",
+ " [keyword function]([def a]) {",
+ " [keyword debugger];",
+ "};");
+
+ MT("indent_below_if",
+ "[keyword for] (;;)",
+ " [keyword if] ([variable foo])",
+ " [number 1];",
+ "[number 2];");
+
+ MT("indent_semicolonless_if",
+ "[keyword function] [def foo]() {",
+ " [keyword if] ([variable x])",
+ " [variable foo]()",
+ "}")
+
+ MT("indent_semicolonless_if_with_statement",
+ "[keyword function] [def foo]() {",
+ " [keyword if] ([variable x])",
+ " [variable foo]()",
+ " [variable bar]()",
+ "}")
+
+ MT("multilinestring",
+ "[keyword var] [def x] [operator =] [string 'foo\\]",
+ "[string bar'];");
+
+ MT("scary_regexp",
+ "[string-2 /foo[[/]]bar/];");
+
+ MT("indent_strange_array",
+ "[keyword var] [def x] [operator =] [[",
+ " [number 1],,",
+ " [number 2],",
+ "]];",
+ "[number 10];");
+
+ MT("param_default",
+ "[keyword function] [def foo]([def x] [operator =] [string-2 `foo${][number 10][string-2 }bar`]) {",
+ " [keyword return] [variable-2 x];",
+ "}");
+
+ MT(
+ "param_destructuring",
+ "[keyword function] [def foo]([def x] [operator =] [string-2 `foo${][number 10][string-2 }bar`]) {",
+ " [keyword return] [variable-2 x];",
+ "}");
+
+ MT("new_target",
+ "[keyword function] [def F]([def target]) {",
+ " [keyword if] ([variable-2 target] [operator &&] [keyword new].[keyword target].[property name]) {",
+ " [keyword return] [keyword new]",
+ " .[keyword target];",
+ " }",
+ "}");
+
+ MT("async",
+ "[keyword async] [keyword function] [def foo]([def args]) { [keyword return] [atom true]; }");
+
+ MT("async_assignment",
+ "[keyword const] [def foo] [operator =] [keyword async] [keyword function] ([def args]) { [keyword return] [atom true]; };");
+
+ MT("async_object",
+ "[keyword let] [def obj] [operator =] { [property async]: [atom false] };");
+
+ // async be highlighet as keyword and foo as def, but it requires potentially expensive look-ahead. See #4173
+ MT("async_object_function",
+ "[keyword let] [def obj] [operator =] { [property async] [property foo]([def args]) { [keyword return] [atom true]; } };");
+
+ MT("async_object_properties",
+ "[keyword let] [def obj] [operator =] {",
+ " [property prop1]: [keyword async] [keyword function] ([def args]) { [keyword return] [atom true]; },",
+ " [property prop2]: [keyword async] [keyword function] ([def args]) { [keyword return] [atom true]; },",
+ " [property prop3]: [keyword async] [keyword function] [def prop3]([def args]) { [keyword return] [atom true]; },",
+ "};");
+
+ MT("async_arrow",
+ "[keyword const] [def foo] [operator =] [keyword async] ([def args]) [operator =>] { [keyword return] [atom true]; };");
+
+ MT("async_jquery",
+ "[variable $].[property ajax]({",
+ " [property url]: [variable url],",
+ " [property async]: [atom true],",
+ " [property method]: [string 'GET']",
+ "});");
+
+ MT("async_variable",
+ "[keyword const] [def async] [operator =] {[property a]: [number 1]};",
+ "[keyword const] [def foo] [operator =] [string-2 `bar ${][variable async].[property a][string-2 }`];")
+
+ MT("bigint", "[number 1n] [operator +] [number 0x1afn] [operator +] [number 0o064n] [operator +] [number 0b100n];")
+
+ MT("async_comment",
+ "[keyword async] [comment /**/] [keyword function] [def foo]([def args]) { [keyword return] [atom true]; }");
+
+ MT("indent_switch",
+ "[keyword switch] ([variable x]) {",
+ " [keyword default]:",
+ " [keyword return] [number 2]",
+ "}")
+
+ MT("regexp_corner_case",
+ "[operator +]{} [operator /] [atom undefined];",
+ "[[[meta ...][string-2 /\\//] ]];",
+ "[keyword void] [string-2 /\\//];",
+ "[keyword do] [string-2 /\\//]; [keyword while] ([number 0]);",
+ "[keyword if] ([number 0]) {} [keyword else] [string-2 /\\//];",
+ "[string-2 `${][variable async][operator ++][string-2 }//`];",
+ "[string-2 `${]{} [operator /] [string-2 /\\//}`];")
+
+ MT("return_eol",
+ "[keyword return]",
+ "{} [string-2 /5/]")
+
+ MT("numeric separator",
+ "[number 123_456];",
+ "[number 0xdead_c0de];",
+ "[number 0o123_456];",
+ "[number 0b1101_1101];",
+ "[number .123_456e0_1];",
+ "[number 1E+123_456];",
+ "[number 12_34_56n];")
+
+ MT("underscore property",
+ "[variable something].[property _property];",
+ "[variable something].[property _123];",
+ "[variable something].[property _for];",
+ "[variable _for];",
+ "[variable _123];")
+
+ var ts_mode = CodeMirror.getMode({indentUnit: 2}, "application/typescript")
+ function TS(name) {
+ test.mode(name, ts_mode, Array.prototype.slice.call(arguments, 1))
+ }
+
+ TS("typescript_extend_type",
+ "[keyword class] [def Foo] [keyword extends] [type Some][operator <][type Type][operator >] {}")
+
+ TS("typescript_arrow_type",
+ "[keyword let] [def x]: ([variable arg]: [type Type]) [operator =>] [type ReturnType]")
+
+ TS("typescript_class",
+ "[keyword class] [def Foo] {",
+ " [keyword public] [keyword static] [property main]() {}",
+ " [keyword private] [property _foo]: [type string];",
+ "}")
+
+ TS("typescript_literal_types",
+ "[keyword import] [keyword *] [keyword as] [def Sequelize] [keyword from] [string 'sequelize'];",
+ "[keyword interface] [def MyAttributes] {",
+ " [property truthy]: [string 'true'] [operator |] [number 1] [operator |] [atom true];",
+ " [property falsy]: [string 'false'] [operator |] [number 0] [operator |] [atom false];",
+ "}",
+ "[keyword interface] [def MyInstance] [keyword extends] [type Sequelize].[type Instance] [operator <] [type MyAttributes] [operator >] {",
+ " [property rawAttributes]: [type MyAttributes];",
+ " [property truthy]: [string 'true'] [operator |] [number 1] [operator |] [atom true];",
+ " [property falsy]: [string 'false'] [operator |] [number 0] [operator |] [atom false];",
+ "}")
+
+ TS("typescript_extend_operators",
+ "[keyword export] [keyword interface] [def UserModel] [keyword extends]",
+ " [type Sequelize].[type Model] [operator <] [type UserInstance], [type UserAttributes] [operator >] {",
+ " [property findById]: (",
+ " [variable userId]: [type number]",
+ " ) [operator =>] [type Promise] [operator <] [type Array] [operator <] { [property id], [property name] } [operator >>];",
+ " [property updateById]: (",
+ " [variable userId]: [type number],",
+ " [variable isActive]: [type boolean]",
+ " ) [operator =>] [type Promise] [operator <] [type AccountHolderNotificationPreferenceInstance] [operator >];",
+ " }")
+
+ TS("typescript_interface_with_const",
+ "[keyword const] [def hello]: {",
+ " [property prop1][operator ?]: [type string];",
+ " [property prop2][operator ?]: [type string];",
+ "} [operator =] {};")
+
+ TS("typescript_double_extend",
+ "[keyword export] [keyword interface] [def UserAttributes] {",
+ " [property id][operator ?]: [type number];",
+ " [property createdAt][operator ?]: [type Date];",
+ "}",
+ "[keyword export] [keyword interface] [def UserInstance] [keyword extends] [type Sequelize].[type Instance][operator <][type UserAttributes][operator >], [type UserAttributes] {",
+ " [property id]: [type number];",
+ " [property createdAt]: [type Date];",
+ "}");
+
+ TS("typescript_index_signature",
+ "[keyword interface] [def A] {",
+ " [[ [variable prop]: [type string] ]]: [type any];",
+ " [property prop1]: [type any];",
+ "}");
+
+ TS("typescript_generic_class",
+ "[keyword class] [def Foo][operator <][type T][operator >] {",
+ " [property bar]() {}",
+ " [property foo](): [type Foo] {}",
+ "}")
+
+ TS("typescript_type_when_keyword",
+ "[keyword export] [keyword type] [type AB] [operator =] [type A] [operator |] [type B];",
+ "[keyword type] [type Flags] [operator =] {",
+ " [property p1]: [type string];",
+ " [property p2]: [type boolean];",
+ "};")
+
+ TS("typescript_type_when_not_keyword",
+ "[keyword class] [def HasType] {",
+ " [property type]: [type string];",
+ " [property constructor]([def type]: [type string]) {",
+ " [keyword this].[property type] [operator =] [variable-2 type];",
+ " }",
+ " [property setType]({ [def type] }: { [property type]: [type string]; }) {",
+ " [keyword this].[property type] [operator =] [variable-2 type];",
+ " }",
+ "}")
+
+ TS("typescript_function_generics",
+ "[keyword function] [def a]() {}",
+ "[keyword function] [def b][operator <][type IA] [keyword extends] [type object], [type IB] [keyword extends] [type object][operator >]() {}",
+ "[keyword function] [def c]() {}")
+
+ TS("typescript_complex_return_type",
+ "[keyword function] [def A]() {",
+ " [keyword return] [keyword this].[property property];",
+ "}",
+ "[keyword function] [def B](): [type Promise][operator <]{ [[ [variable key]: [type string] ]]: [type any] } [operator |] [atom null][operator >] {",
+ " [keyword return] [keyword this].[property property];",
+ "}")
+
+ TS("typescript_complex_type_casting",
+ "[keyword const] [def giftpay] [operator =] [variable config].[property get]([string 'giftpay']) [keyword as] { [[ [variable platformUuid]: [type string] ]]: { [property version]: [type number]; [property apiCode]: [type string]; } };")
+
+ TS("typescript_keyof",
+ "[keyword function] [def x][operator <][type T] [keyword extends] [keyword keyof] [type X][operator >]([def a]: [type T]) {",
+ " [keyword return]")
+
+ TS("typescript_new_typeargs",
+ "[keyword let] [def x] [operator =] [keyword new] [variable Map][operator <][type string], [type Date][operator >]([string-2 `foo${][variable bar][string-2 }`])")
+
+ TS("modifiers",
+ "[keyword class] [def Foo] {",
+ " [keyword public] [keyword abstract] [property bar]() {}",
+ " [property constructor]([keyword readonly] [keyword private] [def x]) {}",
+ "}")
+
+ TS("arrow prop",
+ "({[property a]: [def p] [operator =>] [variable-2 p]})")
+
+ TS("generic in function call",
+ "[keyword this].[property a][operator <][type Type][operator >]([variable foo]);",
+ "[keyword this].[property a][operator <][variable Type][operator >][variable foo];")
+
+ TS("type guard",
+ "[keyword class] [def Appler] {",
+ " [keyword static] [property assertApple]([def fruit]: [type Fruit]): [variable-2 fruit] [keyword is] [type Apple] {",
+ " [keyword if] ([operator !]([variable-2 fruit] [keyword instanceof] [variable Apple]))",
+ " [keyword throw] [keyword new] [variable Error]();",
+ " }",
+ "}")
+
+ TS("type as variable",
+ "[variable type] [operator =] [variable x] [keyword as] [type Bar];");
+
+ TS("enum body",
+ "[keyword export] [keyword const] [keyword enum] [def CodeInspectionResultType] {",
+ " [def ERROR] [operator =] [string 'problem_type_error'],",
+ " [def WARNING] [operator =] [string 'problem_type_warning'],",
+ " [def META],",
+ "}")
+
+ TS("parenthesized type",
+ "[keyword class] [def Foo] {",
+ " [property x] [operator =] [keyword new] [variable A][operator <][type B], [type string][operator |](() [operator =>] [type void])[operator >]();",
+ " [keyword private] [property bar]();",
+ "}")
+
+ TS("abstract class",
+ "[keyword export] [keyword abstract] [keyword class] [def Foo] {}")
+
+ TS("interface without semicolons",
+ "[keyword interface] [def Foo] {",
+ " [property greet]([def x]: [type int]): [type blah]",
+ " [property bar]: [type void]",
+ "}")
+
+ var jsonld_mode = CodeMirror.getMode(
+ {indentUnit: 2},
+ {name: "javascript", jsonld: true}
+ );
+ function LD(name) {
+ test.mode(name, jsonld_mode, Array.prototype.slice.call(arguments, 1));
+ }
+
+ LD("json_ld_keywords",
+ '{',
+ ' [meta "@context"]: {',
+ ' [meta "@base"]: [string "http://example.com"],',
+ ' [meta "@vocab"]: [string "http://xmlns.com/foaf/0.1/"],',
+ ' [property "likesFlavor"]: {',
+ ' [meta "@container"]: [meta "@list"]',
+ ' [meta "@reverse"]: [string "@beFavoriteOf"]',
+ ' },',
+ ' [property "nick"]: { [meta "@container"]: [meta "@set"] },',
+ ' [property "nick"]: { [meta "@container"]: [meta "@index"] }',
+ ' },',
+ ' [meta "@graph"]: [[ {',
+ ' [meta "@id"]: [string "http://dbpedia.org/resource/John_Lennon"],',
+ ' [property "name"]: [string "John Lennon"],',
+ ' [property "modified"]: {',
+ ' [meta "@value"]: [string "2010-05-29T14:17:39+02:00"],',
+ ' [meta "@type"]: [string "http://www.w3.org/2001/XMLSchema#dateTime"]',
+ ' }',
+ ' } ]]',
+ '}');
+
+ LD("json_ld_fake",
+ '{',
+ ' [property "@fake"]: [string "@fake"],',
+ ' [property "@contextual"]: [string "@identifier"],',
+ ' [property "user@domain.com"]: [string "@graphical"],',
+ ' [property "@ID"]: [string "@@ID"]',
+ '}');
+})();
diff --git a/devtools/client/shared/sourceeditor/test/codemirror/mode_test.css b/devtools/client/shared/sourceeditor/test/codemirror/mode_test.css
new file mode 100644
index 0000000000..f83271b4e2
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/codemirror/mode_test.css
@@ -0,0 +1,23 @@
+.mt-output .mt-token {
+ border: 1px solid #ddd;
+ white-space: pre;
+ font-family: "Consolas", monospace;
+ text-align: center;
+}
+
+.mt-output .mt-style {
+ font-size: x-small;
+}
+
+.mt-output .mt-state {
+ font-size: x-small;
+ vertical-align: top;
+}
+
+.mt-output .mt-state-row {
+ display: none;
+}
+
+.mt-state-unhide .mt-output .mt-state-row {
+ display: table-row;
+}
diff --git a/devtools/client/shared/sourceeditor/test/codemirror/mode_test.js b/devtools/client/shared/sourceeditor/test/codemirror/mode_test.js
new file mode 100644
index 0000000000..e7c0cf92ae
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/codemirror/mode_test.js
@@ -0,0 +1,193 @@
+/**
+ * Helper to test CodeMirror highlighting modes. It pretty prints output of the
+ * highlighter and can check against expected styles.
+ *
+ * Mode tests are registered by calling test.mode(testName, mode,
+ * tokens), where mode is a mode object as returned by
+ * CodeMirror.getMode, and tokens is an array of lines that make up
+ * the test.
+ *
+ * These lines are strings, in which styled stretches of code are
+ * enclosed in brackets `[]`, and prefixed by their style. For
+ * example, `[keyword if]`. Brackets in the code itself must be
+ * duplicated to prevent them from being interpreted as token
+ * boundaries. For example `a[[i]]` for `a[i]`. If a token has
+ * multiple styles, the styles must be separated by ampersands, for
+ * example `[tag&error </hmtl>]`.
+ *
+ * See the test.js files in the css, markdown, gfm, and stex mode
+ * directories for examples.
+ */
+(function() {
+ function findSingle(str, pos, ch) {
+ for (;;) {
+ var found = str.indexOf(ch, pos);
+ if (found == -1) return null;
+ if (str.charAt(found + 1) != ch) return found;
+ pos = found + 2;
+ }
+ }
+
+ var styleName = /[\w&-_]+/g;
+ function parseTokens(strs) {
+ var tokens = [], plain = "";
+ for (var i = 0; i < strs.length; ++i) {
+ if (i) plain += "\n";
+ var str = strs[i], pos = 0;
+ while (pos < str.length) {
+ var style = null, text;
+ if (str.charAt(pos) == "[" && str.charAt(pos+1) != "[") {
+ styleName.lastIndex = pos + 1;
+ var m = styleName.exec(str);
+ style = m[0].replace(/&/g, " ");
+ var textStart = pos + style.length + 2;
+ var end = findSingle(str, textStart, "]");
+ if (end == null) throw new Error("Unterminated token at " + pos + " in '" + str + "'" + style);
+ text = str.slice(textStart, end);
+ pos = end + 1;
+ } else {
+ var end = findSingle(str, pos, "[");
+ if (end == null) end = str.length;
+ text = str.slice(pos, end);
+ pos = end;
+ }
+ text = text.replace(/\[\[|\]\]/g, function(s) {return s.charAt(0);});
+ tokens.push({style: style, text: text});
+ plain += text;
+ }
+ }
+ return {tokens: tokens, plain: plain};
+ }
+
+ test.mode = function(name, mode, tokens, modeName) {
+ var data = parseTokens(tokens);
+ return test((modeName || mode.name) + "_" + name, function() {
+ return compare(data.plain, data.tokens, mode);
+ });
+ };
+
+ function esc(str) {
+ return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&#039;");
+ }
+
+ function compare(text, expected, mode) {
+
+ var expectedOutput = [];
+ for (var i = 0; i < expected.length; ++i) {
+ var sty = expected[i].style;
+ if (sty && sty.indexOf(" ")) sty = sty.split(' ').sort().join(' ');
+ expectedOutput.push({style: sty, text: expected[i].text});
+ }
+
+ var observedOutput = highlight(text, mode);
+
+ var s = "";
+ var diff = highlightOutputsDifferent(expectedOutput, observedOutput);
+ if (diff != null) {
+ s += '<div class="mt-test mt-fail">';
+ s += '<pre>' + esc(text) + '</pre>';
+ s += '<div class="cm-s-default">';
+ s += 'expected:';
+ s += prettyPrintOutputTable(expectedOutput, diff);
+ s += 'observed: [<a onclick="this.parentElement.className+=\' mt-state-unhide\'">display states</a>]';
+ s += prettyPrintOutputTable(observedOutput, diff);
+ s += '</div>';
+ s += '</div>';
+ }
+ if (observedOutput.indentFailures) {
+ for (var i = 0; i < observedOutput.indentFailures.length; i++)
+ s += "<div class='mt-test mt-fail'>" + esc(observedOutput.indentFailures[i]) + "</div>";
+ }
+ if (s) throw new Failure(s);
+ }
+
+ function stringify(obj) {
+ function replacer(key, obj) {
+ if (typeof obj == "function") {
+ var m = obj.toString().match(/function\s*[^\s(]*/);
+ return m ? m[0] : "function";
+ }
+ return obj;
+ }
+ if (window.JSON && JSON.stringify)
+ return JSON.stringify(obj, replacer, 2);
+ return "[unsupported]"; // Fail safely if no native JSON.
+ }
+
+ function highlight(string, mode) {
+ var state = mode.startState();
+
+ var lines = string.replace(/\r\n/g,'\n').split('\n');
+ var st = [], pos = 0;
+ for (var i = 0; i < lines.length; ++i) {
+ var line = lines[i], newLine = true;
+ if (mode.indent) {
+ var ws = line.match(/^\s*/)[0];
+ var indent = mode.indent(state, line.slice(ws.length), line);
+ if (indent != CodeMirror.Pass && indent != ws.length)
+ (st.indentFailures || (st.indentFailures = [])).push(
+ "Indentation of line " + (i + 1) + " is " + indent + " (expected " + ws.length + ")");
+ }
+ var stream = new CodeMirror.StringStream(line, 4, {
+ lookAhead: function(n) { return lines[i + n] }
+ });
+ if (line == "" && mode.blankLine) mode.blankLine(state);
+ /* Start copied code from CodeMirror.highlight */
+ while (!stream.eol()) {
+ for (var j = 0; j < 10 && stream.start >= stream.pos; j++)
+ var compare = mode.token(stream, state);
+ if (j == 10)
+ throw new Failure("Failed to advance the stream." + stream.string + " " + stream.pos);
+ var substr = stream.current();
+ if (compare && compare.indexOf(" ") > -1) compare = compare.split(' ').sort().join(' ');
+ stream.start = stream.pos;
+ if (pos && st[pos-1].style == compare && !newLine) {
+ st[pos-1].text += substr;
+ } else if (substr) {
+ st[pos++] = {style: compare, text: substr, state: stringify(state)};
+ }
+ // Give up when line is ridiculously long
+ if (stream.pos > 5000) {
+ st[pos++] = {style: null, text: this.text.slice(stream.pos)};
+ break;
+ }
+ newLine = false;
+ }
+ }
+
+ return st;
+ }
+
+ function highlightOutputsDifferent(o1, o2) {
+ var minLen = Math.min(o1.length, o2.length);
+ for (var i = 0; i < minLen; ++i)
+ if (o1[i].style != o2[i].style || o1[i].text != o2[i].text) return i;
+ if (o1.length > minLen || o2.length > minLen) return minLen;
+ }
+
+ function prettyPrintOutputTable(output, diffAt) {
+ var s = '<table class="mt-output">';
+ s += '<tr>';
+ for (var i = 0; i < output.length; ++i) {
+ var style = output[i].style, val = output[i].text;
+ s +=
+ '<td class="mt-token"' + (i == diffAt ? " style='background: pink'" : "") + '>' +
+ '<span class="cm-' + esc(String(style)) + '">' +
+ esc(val.replace(/ /g,'\xb7')) + // · MIDDLE DOT
+ '</span>' +
+ '</td>';
+ }
+ s += '</tr><tr>';
+ for (var i = 0; i < output.length; ++i) {
+ s += '<td class="mt-style"><span>' + (output[i].style || null) + '</span></td>';
+ }
+ if(output[0].state) {
+ s += '</tr><tr class="mt-state-row" title="State AFTER each token">';
+ for (var i = 0; i < output.length; ++i) {
+ s += '<td class="mt-state"><pre>' + esc(output[i].state) + '</pre></td>';
+ }
+ }
+ s += '</tr></table>';
+ return s;
+ }
+})();
diff --git a/devtools/client/shared/sourceeditor/test/codemirror/multi_test.js b/devtools/client/shared/sourceeditor/test/codemirror/multi_test.js
new file mode 100644
index 0000000000..cc042f7399
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/codemirror/multi_test.js
@@ -0,0 +1,295 @@
+(function() {
+ namespace = "multi_";
+
+ function hasSelections(cm) {
+ var sels = cm.listSelections();
+ var given = (arguments.length - 1) / 4;
+ if (sels.length != given)
+ throw new Failure("expected " + given + " selections, found " + sels.length);
+ for (var i = 0, p = 1; i < given; i++, p += 4) {
+ var anchor = Pos(arguments[p], arguments[p + 1]);
+ var head = Pos(arguments[p + 2], arguments[p + 3]);
+ eqCharPos(sels[i].anchor, anchor, "anchor of selection " + i);
+ eqCharPos(sels[i].head, head, "head of selection " + i);
+ }
+ }
+ function hasCursors(cm) {
+ var sels = cm.listSelections();
+ var given = (arguments.length - 1) / 2;
+ if (sels.length != given)
+ throw new Failure("expected " + given + " selections, found " + sels.length);
+ for (var i = 0, p = 1; i < given; i++, p += 2) {
+ eqCursorPos(sels[i].anchor, sels[i].head, "something selected for " + i);
+ var head = Pos(arguments[p], arguments[p + 1]);
+ eqCharPos(sels[i].head, head, "selection " + i);
+ }
+ }
+
+ testCM("getSelection", function(cm) {
+ select(cm, {anchor: Pos(0, 0), head: Pos(1, 2)}, {anchor: Pos(2, 2), head: Pos(2, 0)});
+ eq(cm.getSelection(), "1234\n56\n90");
+ eq(cm.getSelection(false).join("|"), "1234|56|90");
+ eq(cm.getSelections().join("|"), "1234\n56|90");
+ }, {value: "1234\n5678\n90"});
+
+ testCM("setSelection", function(cm) {
+ select(cm, Pos(3, 0), Pos(0, 0), {anchor: Pos(2, 5), head: Pos(1, 0)});
+ hasSelections(cm, 0, 0, 0, 0,
+ 2, 5, 1, 0,
+ 3, 0, 3, 0);
+ cm.setSelection(Pos(1, 2), Pos(1, 1));
+ hasSelections(cm, 1, 2, 1, 1);
+ select(cm, {anchor: Pos(1, 1), head: Pos(2, 4)},
+ {anchor: Pos(0, 0), head: Pos(1, 3)},
+ Pos(3, 0), Pos(2, 2));
+ hasSelections(cm, 0, 0, 2, 4,
+ 3, 0, 3, 0);
+ cm.setSelections([{anchor: Pos(0, 1), head: Pos(0, 2)},
+ {anchor: Pos(1, 1), head: Pos(1, 2)},
+ {anchor: Pos(2, 1), head: Pos(2, 2)}], 1);
+ eqCharPos(cm.getCursor("head"), Pos(1, 2));
+ eqCharPos(cm.getCursor("anchor"), Pos(1, 1));
+ eqCharPos(cm.getCursor("from"), Pos(1, 1));
+ eqCharPos(cm.getCursor("to"), Pos(1, 2));
+ cm.setCursor(Pos(1, 1));
+ hasCursors(cm, 1, 1);
+ }, {value: "abcde\nabcde\nabcde\n"});
+
+ testCM("somethingSelected", function(cm) {
+ select(cm, Pos(0, 1), {anchor: Pos(0, 3), head: Pos(0, 5)});
+ eq(cm.somethingSelected(), true);
+ select(cm, Pos(0, 1), Pos(0, 3), Pos(0, 5));
+ eq(cm.somethingSelected(), false);
+ }, {value: "123456789"});
+
+ testCM("extendSelection", function(cm) {
+ select(cm, Pos(0, 1), Pos(1, 1), Pos(2, 1));
+ cm.setExtending(true);
+ cm.extendSelections([Pos(0, 2), Pos(1, 0), Pos(2, 3)]);
+ hasSelections(cm, 0, 1, 0, 2,
+ 1, 1, 1, 0,
+ 2, 1, 2, 3);
+ cm.extendSelection(Pos(2, 4), Pos(2, 0));
+ hasSelections(cm, 2, 4, 2, 0);
+ }, {value: "1234\n1234\n1234"});
+
+ testCM("addSelection", function(cm) {
+ select(cm, Pos(0, 1), Pos(1, 1));
+ cm.addSelection(Pos(0, 0), Pos(0, 4));
+ hasSelections(cm, 0, 0, 0, 4,
+ 1, 1, 1, 1);
+ cm.addSelection(Pos(2, 2));
+ hasSelections(cm, 0, 0, 0, 4,
+ 1, 1, 1, 1,
+ 2, 2, 2, 2);
+ }, {value: "1234\n1234\n1234"});
+
+ testCM("replaceSelection", function(cm) {
+ var selections = [{anchor: Pos(0, 0), head: Pos(0, 1)},
+ {anchor: Pos(0, 2), head: Pos(0, 3)},
+ {anchor: Pos(0, 4), head: Pos(0, 5)},
+ {anchor: Pos(2, 1), head: Pos(2, 4)},
+ {anchor: Pos(2, 5), head: Pos(2, 6)}];
+ var val = "123456\n123456\n123456";
+ cm.setValue(val);
+ cm.setSelections(selections);
+ cm.replaceSelection("ab", "around");
+ eq(cm.getValue(), "ab2ab4ab6\n123456\n1ab5ab");
+ hasSelections(cm, 0, 0, 0, 2,
+ 0, 3, 0, 5,
+ 0, 6, 0, 8,
+ 2, 1, 2, 3,
+ 2, 4, 2, 6);
+ cm.setValue(val);
+ cm.setSelections(selections);
+ cm.replaceSelection("", "around");
+ eq(cm.getValue(), "246\n123456\n15");
+ hasSelections(cm, 0, 0, 0, 0,
+ 0, 1, 0, 1,
+ 0, 2, 0, 2,
+ 2, 1, 2, 1,
+ 2, 2, 2, 2);
+ cm.setValue(val);
+ cm.setSelections(selections);
+ cm.replaceSelection("X\nY\nZ", "around");
+ hasSelections(cm, 0, 0, 2, 1,
+ 2, 2, 4, 1,
+ 4, 2, 6, 1,
+ 8, 1, 10, 1,
+ 10, 2, 12, 1);
+ cm.replaceSelection("a", "around");
+ hasSelections(cm, 0, 0, 0, 1,
+ 0, 2, 0, 3,
+ 0, 4, 0, 5,
+ 2, 1, 2, 2,
+ 2, 3, 2, 4);
+ cm.replaceSelection("xy", "start");
+ hasSelections(cm, 0, 0, 0, 0,
+ 0, 3, 0, 3,
+ 0, 6, 0, 6,
+ 2, 1, 2, 1,
+ 2, 4, 2, 4);
+ cm.replaceSelection("z\nf");
+ hasSelections(cm, 1, 1, 1, 1,
+ 2, 1, 2, 1,
+ 3, 1, 3, 1,
+ 6, 1, 6, 1,
+ 7, 1, 7, 1);
+ eq(cm.getValue(), "z\nfxy2z\nfxy4z\nfxy6\n123456\n1z\nfxy5z\nfxy");
+ });
+
+ function select(cm) {
+ var sels = [];
+ for (var i = 1; i < arguments.length; i++) {
+ var arg = arguments[i];
+ if (arg.head) sels.push(arg);
+ else sels.push({head: arg, anchor: arg});
+ }
+ cm.setSelections(sels, sels.length - 1);
+ }
+
+ testCM("indentSelection", function(cm) {
+ select(cm, Pos(0, 1), Pos(1, 1));
+ cm.indentSelection(4);
+ eq(cm.getValue(), " foo\n bar\nbaz");
+
+ select(cm, Pos(0, 2), Pos(0, 3), Pos(0, 4));
+ cm.indentSelection(-2);
+ eq(cm.getValue(), " foo\n bar\nbaz");
+
+ select(cm, {anchor: Pos(0, 0), head: Pos(1, 2)},
+ {anchor: Pos(1, 3), head: Pos(2, 0)});
+ cm.indentSelection(-2);
+ eq(cm.getValue(), "foo\n bar\nbaz");
+ }, {value: "foo\nbar\nbaz"});
+
+ testCM("killLine", function(cm) {
+ select(cm, Pos(0, 1), Pos(0, 2), Pos(1, 1));
+ cm.execCommand("killLine");
+ eq(cm.getValue(), "f\nb\nbaz");
+ cm.execCommand("killLine");
+ eq(cm.getValue(), "fbbaz");
+ cm.setValue("foo\nbar\nbaz");
+ select(cm, Pos(0, 1), {anchor: Pos(0, 2), head: Pos(2, 1)});
+ cm.execCommand("killLine");
+ eq(cm.getValue(), "faz");
+ }, {value: "foo\nbar\nbaz"});
+
+ testCM("deleteLine", function(cm) {
+ select(cm, Pos(0, 0),
+ {head: Pos(0, 1), anchor: Pos(2, 0)},
+ Pos(4, 0));
+ cm.execCommand("deleteLine");
+ eq(cm.getValue(), "4\n6\n7");
+ select(cm, Pos(2, 1));
+ cm.execCommand("deleteLine");
+ eq(cm.getValue(), "4\n6\n");
+ }, {value: "1\n2\n3\n4\n5\n6\n7"});
+
+ testCM("deleteH", function(cm) {
+ select(cm, Pos(0, 4), {anchor: Pos(1, 4), head: Pos(1, 5)});
+ cm.execCommand("delWordAfter");
+ eq(cm.getValue(), "foo bar baz\nabc ef ghi\n");
+ cm.execCommand("delWordAfter");
+ eq(cm.getValue(), "foo baz\nabc ghi\n");
+ cm.execCommand("delCharBefore");
+ cm.execCommand("delCharBefore");
+ eq(cm.getValue(), "fo baz\nab ghi\n");
+ select(cm, Pos(0, 3), Pos(0, 4), Pos(0, 5));
+ cm.execCommand("delWordAfter");
+ eq(cm.getValue(), "fo \nab ghi\n");
+ }, {value: "foo bar baz\nabc def ghi\n"});
+
+ testCM("goLineStart", function(cm) {
+ select(cm, Pos(0, 2), Pos(0, 3), Pos(1, 1));
+ cm.execCommand("goLineStart");
+ hasCursors(cm, 0, 0, 1, 0);
+ select(cm, Pos(1, 1), Pos(0, 1));
+ cm.setExtending(true);
+ cm.execCommand("goLineStart");
+ hasSelections(cm, 0, 1, 0, 0,
+ 1, 1, 1, 0);
+ }, {value: "foo\nbar\nbaz"});
+
+ testCM("moveV", function(cm) {
+ select(cm, Pos(0, 2), Pos(1, 2));
+ cm.execCommand("goLineDown");
+ hasCursors(cm, 1, 2, 2, 2);
+ cm.execCommand("goLineUp");
+ hasCursors(cm, 0, 2, 1, 2);
+ cm.execCommand("goLineUp");
+ hasCursors(cm, 0, 0, 0, 2);
+ cm.execCommand("goLineUp");
+ hasCursors(cm, 0, 0);
+ select(cm, Pos(0, 2), Pos(1, 2));
+ cm.setExtending(true);
+ cm.execCommand("goLineDown");
+ hasSelections(cm, 0, 2, 2, 2);
+ }, {value: "12345\n12345\n12345"});
+
+ testCM("moveH", function(cm) {
+ select(cm, Pos(0, 1), Pos(0, 3), Pos(0, 5), Pos(2, 3));
+ cm.execCommand("goCharRight");
+ hasCursors(cm, 0, 2, 0, 4, 1, 0, 2, 4);
+ cm.execCommand("goCharLeft");
+ hasCursors(cm, 0, 1, 0, 3, 0, 5, 2, 3);
+ for (var i = 0; i < 15; i++)
+ cm.execCommand("goCharRight");
+ hasCursors(cm, 2, 4, 2, 5);
+ }, {value: "12345\n12345\n12345"});
+
+ testCM("newlineAndIndent", function(cm) {
+ select(cm, Pos(0, 5), Pos(1, 5));
+ cm.execCommand("newlineAndIndent");
+ hasCursors(cm, 1, 2, 3, 2);
+ eq(cm.getValue(), "x = [\n 1];\ny = [\n 2];");
+ cm.undo();
+ eq(cm.getValue(), "x = [1];\ny = [2];");
+ hasCursors(cm, 0, 5, 1, 5);
+ select(cm, Pos(0, 5), Pos(0, 6));
+ cm.execCommand("newlineAndIndent");
+ hasCursors(cm, 1, 2, 2, 0);
+ eq(cm.getValue(), "x = [\n 1\n];\ny = [2];");
+ }, {value: "x = [1];\ny = [2];", mode: "javascript"});
+
+ testCM("goDocStartEnd", function(cm) {
+ select(cm, Pos(0, 1), Pos(1, 1));
+ cm.execCommand("goDocStart");
+ hasCursors(cm, 0, 0);
+ select(cm, Pos(0, 1), Pos(1, 1));
+ cm.execCommand("goDocEnd");
+ hasCursors(cm, 1, 3);
+ select(cm, Pos(0, 1), Pos(1, 1));
+ cm.setExtending(true);
+ cm.execCommand("goDocEnd");
+ hasSelections(cm, 1, 1, 1, 3);
+ }, {value: "abc\ndef"});
+
+ testCM("selectionHistory", function(cm) {
+ for (var i = 0; i < 3; ++i)
+ cm.addSelection(Pos(0, i * 2), Pos(0, i * 2 + 1));
+ cm.execCommand("undoSelection");
+ eq(cm.getSelection(), "1\n2");
+ cm.execCommand("undoSelection");
+ eq(cm.getSelection(), "1");
+ cm.execCommand("undoSelection");
+ eq(cm.getSelection(), "");
+ eqCharPos(cm.getCursor(), Pos(0, 0));
+ cm.execCommand("redoSelection");
+ eq(cm.getSelection(), "1");
+ cm.execCommand("redoSelection");
+ eq(cm.getSelection(), "1\n2");
+ cm.execCommand("redoSelection");
+ eq(cm.getSelection(), "1\n2\n3");
+ }, {value: "1 2 3"});
+
+ testCM("selectionsMayTouch", function(cm) {
+ select(cm, Pos(0, 0), Pos(0, 2))
+ cm.setExtending(true);
+ cm.extendSelections([Pos(0, 2), Pos(0, 4)])
+ hasSelections(cm, 0, 0, 0, 2,
+ 0, 2, 0, 4)
+ cm.extendSelections([Pos(0, 3), Pos(0, 4)])
+ hasSelections(cm, 0, 0, 0, 4)
+ }, {selectionsMayTouch: true, value: "1234"})
+})();
diff --git a/devtools/client/shared/sourceeditor/test/codemirror/search_test.js b/devtools/client/shared/sourceeditor/test/codemirror/search_test.js
new file mode 100644
index 0000000000..e3188de529
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/codemirror/search_test.js
@@ -0,0 +1,85 @@
+(function() {
+ "use strict";
+
+ function run(doc, query, options) {
+ var cursor = doc.getSearchCursor(query, null, options);
+ for (var i = 3; i < arguments.length; i += 4) {
+ var found = cursor.findNext();
+ is(found, "not enough results (forward)");
+ eqCharPos(Pos(arguments[i], arguments[i + 1]), cursor.from(), "from, forward, " + (i - 3) / 4);
+ eqCharPos(Pos(arguments[i + 2], arguments[i + 3]), cursor.to(), "to, forward, " + (i - 3) / 4);
+ }
+ is(!cursor.findNext(), "too many matches (forward)");
+ for (var i = arguments.length - 4; i >= 3; i -= 4) {
+ var found = cursor.findPrevious();
+ is(found, "not enough results (backwards)");
+ eqCharPos(Pos(arguments[i], arguments[i + 1]), cursor.from(), "from, backwards, " + (i - 3) / 4);
+ eqCharPos(Pos(arguments[i + 2], arguments[i + 3]), cursor.to(), "to, backwards, " + (i - 3) / 4);
+ }
+ is(!cursor.findPrevious(), "too many matches (backwards)");
+ }
+
+ function test(name, f) { window.test("search_" + name, f) }
+
+ test("simple", function() {
+ var doc = new CodeMirror.Doc("abcdefg\nabcdefg")
+ run(doc, "cde", false, 0, 2, 0, 5, 1, 2, 1, 5);
+ });
+
+ test("multiline", function() {
+ var doc = new CodeMirror.Doc("hallo\na\nb\ngoodbye")
+ run(doc, "llo\na\nb\ngoo", false, 0, 2, 3, 3);
+ run(doc, "blah\na\nb\nhall", false);
+ run(doc, "bye\nx\neye", false);
+ });
+
+ test("regexp", function() {
+ var doc = new CodeMirror.Doc("abcde\nabcde")
+ run(doc, /bcd/, false, 0, 1, 0, 4, 1, 1, 1, 4);
+ run(doc, /BCD/, false);
+ run(doc, /BCD/i, false, 0, 1, 0, 4, 1, 1, 1, 4);
+ });
+
+ test("regexpMultiline", function() {
+ var doc = new CodeMirror.Doc("foo foo\nbar\nbaz")
+ run(doc, /fo[^]*az/, {multiline: true}, 0, 0, 2, 3)
+ run(doc, /[oa][^u]/, {multiline: true}, 0, 1, 0, 3, 0, 5, 0, 7, 1, 1, 1, 3, 2, 1, 2, 3)
+ run(doc, /[a][^u]{2}/, {multiline: true}, 1, 1, 2, 0)
+ })
+
+ test("insensitive", function() {
+ var doc = new CodeMirror.Doc("hallo\nHALLO\noink\nhAllO")
+ run(doc, "All", false, 3, 1, 3, 4);
+ run(doc, "All", true, 0, 1, 0, 4, 1, 1, 1, 4, 3, 1, 3, 4);
+ });
+
+ test("multilineInsensitive", function() {
+ var doc = new CodeMirror.Doc("zie ginds komT\nDe Stoomboot\nuit Spanje weer aan")
+ run(doc, "komt\nde stoomboot\nuit", false);
+ run(doc, "komt\nde stoomboot\nuit", {caseFold: true}, 0, 10, 2, 3);
+ run(doc, "kOMt\ndE stOOmboot\nuiT", {caseFold: true}, 0, 10, 2, 3);
+ });
+
+ test("multilineInsensitiveSlow", function() {
+ var text = ""
+ for (var i = 0; i < 1000; i++) text += "foo\nbar\n"
+ var doc = new CodeMirror.Doc("find\nme\n" + text + "find\nme\n")
+ var t0 = +new Date
+ run(doc, /find\nme/, {multiline: true}, 0, 0, 1, 2, 2002, 0, 2003, 2)
+ is(+new Date - t0 < 100)
+ })
+
+ test("expandingCaseFold", function() {
+ var doc = new CodeMirror.Doc("<b>İİ İİ</b>\n<b>uu uu</b>")
+ run(doc, "</b>", true, 0, 8, 0, 12, 1, 8, 1, 12);
+ run(doc, "İİ", true, 0, 3, 0, 5, 0, 6, 0, 8);
+ });
+
+ test("normalize", function() {
+ if (!String.prototype.normalize) return
+ var doc = new CodeMirror.Doc("yılbaşı\n수 있을까\nLe taux d'humidité à London")
+ run(doc, "s", false, 0, 5, 0, 6)
+ run(doc, "이", false, 1, 2, 1, 3)
+ run(doc, "a", false, 0, 4, 0, 5, 2, 4, 2, 5, 2, 19, 2, 20)
+ })
+})();
diff --git a/devtools/client/shared/sourceeditor/test/codemirror/sublime_test.js b/devtools/client/shared/sourceeditor/test/codemirror/sublime_test.js
new file mode 100644
index 0000000000..09bb951247
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/codemirror/sublime_test.js
@@ -0,0 +1,284 @@
+(function() {
+ "use strict";
+
+ var Pos = CodeMirror.Pos;
+ namespace = "sublime_";
+
+ function stTest(name) {
+ var actions = Array.prototype.slice.call(arguments, 1);
+ testCM(name, function(cm) {
+ for (var i = 0; i < actions.length; i++) {
+ var action = actions[i];
+ if (typeof action == "string" && i == 0)
+ cm.setValue(action);
+ else if (typeof action == "string")
+ cm.execCommand(action);
+ else if (action instanceof Pos)
+ cm.setCursor(action);
+ else
+ action(cm);
+ }
+ });
+ }
+
+ function at(line, ch, msg) {
+ return function(cm) {
+ eq(cm.listSelections().length, 1);
+ eqCursorPos(cm.getCursor("head"), Pos(line, ch), msg);
+ eqCursorPos(cm.getCursor("anchor"), Pos(line, ch), msg);
+ };
+ }
+
+ function val(content, msg) {
+ return function(cm) { eq(cm.getValue(), content, msg); };
+ }
+
+ function argsToRanges(args) {
+ if (args.length % 4) throw new Error("Wrong number of arguments for ranges.");
+ var ranges = [];
+ for (var i = 0; i < args.length; i += 4)
+ ranges.push({anchor: Pos(args[i], args[i + 1]),
+ head: Pos(args[i + 2], args[i + 3])});
+ return ranges;
+ }
+
+ function setSel() {
+ var ranges = argsToRanges(arguments);
+ return function(cm) { cm.setSelections(ranges, 0); };
+ }
+
+ function hasSel() {
+ var ranges = argsToRanges(arguments);
+ return function(cm) {
+ var sels = cm.listSelections();
+ if (sels.length != ranges.length)
+ throw new Failure("Expected " + ranges.length + " selections, but found " + sels.length);
+ for (var i = 0; i < sels.length; i++) {
+ eqCharPos(sels[i].anchor, ranges[i].anchor, "anchor " + i);
+ eqCharPos(sels[i].head, ranges[i].head, "head " + i);
+ }
+ };
+ }
+
+ stTest("bySubword", "the foo_bar DooDahBah \n a",
+ "goSubwordLeft", at(0, 0),
+ "goSubwordRight", at(0, 3),
+ "goSubwordRight", at(0, 7),
+ "goSubwordRight", at(0, 11),
+ "goSubwordRight", at(0, 15),
+ "goSubwordRight", at(0, 18),
+ "goSubwordRight", at(0, 21),
+ "goSubwordRight", at(0, 22),
+ "goSubwordRight", at(1, 0),
+ "goSubwordRight", at(1, 2),
+ "goSubwordRight", at(1, 2),
+ "goSubwordLeft", at(1, 1),
+ "goSubwordLeft", at(1, 0),
+ "goSubwordLeft", at(0, 22),
+ "goSubwordLeft", at(0, 18),
+ "goSubwordLeft", at(0, 15),
+ "goSubwordLeft", at(0, 12),
+ "goSubwordLeft", at(0, 8),
+ "goSubwordLeft", at(0, 4),
+ "goSubwordLeft", at(0, 0));
+
+ stTest("splitSelectionByLine", "abc\ndef\nghi",
+ setSel(0, 1, 2, 2),
+ "splitSelectionByLine",
+ hasSel(0, 1, 0, 3,
+ 1, 0, 1, 3,
+ 2, 0, 2, 2));
+
+ stTest("splitSelectionByLineMulti", "abc\ndef\nghi\njkl",
+ setSel(0, 1, 1, 1,
+ 1, 2, 3, 2,
+ 3, 3, 3, 3),
+ "splitSelectionByLine",
+ hasSel(0, 1, 0, 3,
+ 1, 0, 1, 1,
+ 1, 2, 1, 3,
+ 2, 0, 2, 3,
+ 3, 0, 3, 2,
+ 3, 3, 3, 3));
+
+ stTest("selectLine", "abc\ndef\nghi",
+ setSel(0, 1, 0, 1,
+ 2, 0, 2, 1),
+ "selectLine",
+ hasSel(0, 0, 1, 0,
+ 2, 0, 2, 3),
+ setSel(0, 1, 1, 0),
+ "selectLine",
+ hasSel(0, 0, 2, 0));
+
+ stTest("insertLineAfter", "abcde\nfghijkl\nmn",
+ setSel(0, 1, 0, 1,
+ 0, 3, 0, 3,
+ 1, 2, 1, 2,
+ 1, 3, 1, 5), "insertLineAfter",
+ hasSel(1, 0, 1, 0,
+ 3, 0, 3, 0), val("abcde\n\nfghijkl\n\nmn"));
+
+ stTest("insertLineBefore", "abcde\nfghijkl\nmn",
+ setSel(0, 1, 0, 1,
+ 0, 3, 0, 3,
+ 1, 2, 1, 2,
+ 1, 3, 1, 5), "insertLineBefore",
+ hasSel(0, 0, 0, 0,
+ 2, 0, 2, 0), val("\nabcde\n\nfghijkl\nmn"));
+
+ stTest("selectNextOccurrence", "a foo bar\nfoobar foo",
+ setSel(0, 2, 0, 5),
+ "selectNextOccurrence", hasSel(0, 2, 0, 5,
+ 1, 0, 1, 3),
+ "selectNextOccurrence", hasSel(0, 2, 0, 5,
+ 1, 0, 1, 3,
+ 1, 7, 1, 10),
+ "selectNextOccurrence", hasSel(0, 2, 0, 5,
+ 1, 0, 1, 3,
+ 1, 7, 1, 10),
+ Pos(0, 3), "selectNextOccurrence", hasSel(0, 2, 0, 5),
+ "selectNextOccurrence", hasSel(0, 2, 0, 5,
+ 1, 7, 1, 10),
+ setSel(0, 6, 0, 9),
+ "selectNextOccurrence", hasSel(0, 6, 0, 9,
+ 1, 3, 1, 6));
+
+ stTest("selectScope", "foo(a) {\n bar[1, 2];\n}",
+ "selectScope", hasSel(0, 0, 2, 1),
+ Pos(0, 4), "selectScope", hasSel(0, 4, 0, 5),
+ Pos(0, 5), "selectScope", hasSel(0, 4, 0, 5),
+ Pos(0, 6), "selectScope", hasSel(0, 0, 2, 1),
+ Pos(0, 8), "selectScope", hasSel(0, 8, 2, 0),
+ Pos(1, 2), "selectScope", hasSel(0, 8, 2, 0),
+ Pos(1, 6), "selectScope", hasSel(1, 6, 1, 10),
+ Pos(1, 9), "selectScope", hasSel(1, 6, 1, 10),
+ "selectScope", hasSel(0, 8, 2, 0),
+ "selectScope", hasSel(0, 0, 2, 1));
+
+ stTest("goToBracket", "foo(a) {\n bar[1, 2];\n}",
+ Pos(0, 0), "goToBracket", at(0, 0),
+ Pos(0, 4), "goToBracket", at(0, 5), "goToBracket", at(0, 4),
+ Pos(0, 8), "goToBracket", at(2, 0), "goToBracket", at(0, 8),
+ Pos(1, 2), "goToBracket", at(2, 0),
+ Pos(1, 7), "goToBracket", at(1, 10), "goToBracket", at(1, 6));
+
+ stTest("swapLine", "1\n2\n3---\n4\n5",
+ "swapLineDown", val("2\n1\n3---\n4\n5"),
+ "swapLineUp", val("1\n2\n3---\n4\n5"),
+ "swapLineUp", val("1\n2\n3---\n4\n5"),
+ Pos(4, 1), "swapLineDown", val("1\n2\n3---\n4\n5"),
+ setSel(0, 1, 0, 1,
+ 1, 0, 2, 0,
+ 2, 2, 2, 2),
+ "swapLineDown", val("4\n1\n2\n3---\n5"),
+ hasSel(1, 1, 1, 1,
+ 2, 0, 3, 0,
+ 3, 2, 3, 2),
+ "swapLineUp", val("1\n2\n3---\n4\n5"),
+ hasSel(0, 1, 0, 1,
+ 1, 0, 2, 0,
+ 2, 2, 2, 2));
+
+ stTest("swapLineEmptyBottomSel", "1\n2\n3",
+ setSel(0, 1, 1, 0),
+ "swapLineDown", val("2\n1\n3"), hasSel(1, 1, 2, 0),
+ "swapLineUp", val("1\n2\n3"), hasSel(0, 1, 1, 0),
+ "swapLineUp", val("1\n2\n3"), hasSel(0, 0, 0, 0));
+
+ stTest("swapLineUpFromEnd", "a\nb\nc",
+ Pos(2, 1), "swapLineUp",
+ hasSel(1, 1, 1, 1), val("a\nc\nb"));
+
+ stTest("joinLines", "abc\ndef\nghi\njkl",
+ "joinLines", val("abc def\nghi\njkl"), at(0, 4),
+ "undo",
+ setSel(0, 2, 1, 1), "joinLines",
+ val("abc def ghi\njkl"), hasSel(0, 2, 0, 8),
+ "undo",
+ setSel(0, 1, 0, 1,
+ 1, 1, 1, 1,
+ 3, 1, 3, 1), "joinLines",
+ val("abc def ghi\njkl"), hasSel(0, 4, 0, 4,
+ 0, 8, 0, 8,
+ 1, 3, 1, 3));
+
+ stTest("duplicateLine", "abc\ndef\nghi",
+ Pos(1, 0), "duplicateLine", val("abc\ndef\ndef\nghi"), at(2, 0),
+ "undo",
+ setSel(0, 1, 0, 1,
+ 1, 1, 1, 1,
+ 2, 1, 2, 1), "duplicateLine",
+ val("abc\nabc\ndef\ndef\nghi\nghi"), hasSel(1, 1, 1, 1,
+ 3, 1, 3, 1,
+ 5, 1, 5, 1));
+ stTest("duplicateLineSelection", "abcdef",
+ setSel(0, 1, 0, 1,
+ 0, 2, 0, 4,
+ 0, 5, 0, 5),
+ "duplicateLine",
+ val("abcdef\nabcdcdef\nabcdcdef"), hasSel(2, 1, 2, 1,
+ 2, 4, 2, 6,
+ 2, 7, 2, 7));
+
+ stTest("sortLines", "c\nb\na\nC\nB\nA",
+ "sortLines", val("A\nB\nC\na\nb\nc"),
+ "undo",
+ setSel(0, 0, 2, 0,
+ 3, 0, 5, 0),
+ "sortLines", val("b\nc\na\nB\nC\nA"),
+ hasSel(0, 0, 2, 0,
+ 3, 0, 5, 0),
+ "undo",
+ setSel(1, 0, 5, 0), "sortLinesInsensitive", val("c\na\nB\nb\nC\nA"));
+
+ stTest("bookmarks", "abc\ndef\nghi\njkl",
+ Pos(0, 1), "toggleBookmark",
+ setSel(1, 1, 1, 2), "toggleBookmark",
+ setSel(2, 1, 2, 2), "toggleBookmark",
+ "nextBookmark", hasSel(0, 1, 0, 1),
+ "nextBookmark", hasSel(1, 1, 1, 2),
+ "nextBookmark", hasSel(2, 1, 2, 2),
+ "prevBookmark", hasSel(1, 1, 1, 2),
+ "prevBookmark", hasSel(0, 1, 0, 1),
+ "prevBookmark", hasSel(2, 1, 2, 2),
+ "prevBookmark", hasSel(1, 1, 1, 2),
+ "toggleBookmark",
+ "prevBookmark", hasSel(2, 1, 2, 2),
+ "prevBookmark", hasSel(0, 1, 0, 1),
+ "selectBookmarks", hasSel(0, 1, 0, 1,
+ 2, 1, 2, 2),
+ "clearBookmarks",
+ Pos(0, 0), "selectBookmarks", at(0, 0));
+
+ stTest("smartBackspace", " foo\n bar",
+ setSel(0, 2, 0, 2, 1, 4, 1, 4, 1, 6, 1, 6), "smartBackspace",
+ val("foo\n br"))
+
+ stTest("upAndDowncaseAtCursor", "abc\ndef x\nghI",
+ setSel(0, 1, 0, 3,
+ 1, 1, 1, 1,
+ 1, 4, 1, 4), "upcaseAtCursor",
+ val("aBC\nDEF x\nghI"), hasSel(0, 1, 0, 3,
+ 1, 3, 1, 3,
+ 1, 4, 1, 4),
+ "downcaseAtCursor",
+ val("abc\ndef x\nghI"), hasSel(0, 1, 0, 3,
+ 1, 3, 1, 3,
+ 1, 4, 1, 4));
+
+ stTest("mark", "abc\ndef\nghi",
+ Pos(1, 1), "setSublimeMark",
+ Pos(2, 1), "selectToSublimeMark", hasSel(2, 1, 1, 1),
+ Pos(0, 1), "swapWithSublimeMark", at(1, 1), "swapWithSublimeMark", at(0, 1),
+ "deleteToSublimeMark", val("aef\nghi"),
+ "sublimeYank", val("abc\ndef\nghi"), at(1, 1));
+
+ stTest("findUnder", "foo foobar a",
+ "findUnder", hasSel(0, 4, 0, 7),
+ "findUnder", hasSel(0, 0, 0, 3),
+ "findUnderPrevious", hasSel(0, 4, 0, 7),
+ "findUnderPrevious", hasSel(0, 0, 0, 3),
+ Pos(0, 4), "findUnder", hasSel(0, 4, 0, 10),
+ Pos(0, 11), "findUnder", hasSel(0, 11, 0, 11));
+})();
diff --git a/devtools/client/shared/sourceeditor/test/codemirror/test.js b/devtools/client/shared/sourceeditor/test/codemirror/test.js
new file mode 100644
index 0000000000..846d94e8a9
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/codemirror/test.js
@@ -0,0 +1,2686 @@
+var Pos = CodeMirror.Pos;
+
+CodeMirror.defaults.rtlMoveVisually = true;
+
+function forEach(arr, f) {
+ for (var i = 0, e = arr.length; i < e; ++i) f(arr[i], i);
+}
+
+function addDoc(cm, width, height) {
+ var content = [], line = "";
+ for (var i = 0; i < width; ++i) line += "x";
+ for (var i = 0; i < height; ++i) content.push(line);
+ cm.setValue(content.join("\n"));
+}
+
+function byClassName(elt, cls) {
+ if (elt.getElementsByClassName) return elt.getElementsByClassName(cls);
+ var found = [], re = new RegExp("\\b" + cls + "\\b");
+ function search(elt) {
+ if (elt.nodeType == 3) return;
+ if (re.test(elt.className)) found.push(elt);
+ for (var i = 0, e = elt.childNodes.length; i < e; ++i)
+ search(elt.childNodes[i]);
+ }
+ search(elt);
+ return found;
+}
+
+var ie_lt8 = /MSIE [1-7]\b/.test(navigator.userAgent);
+var ie_lt9 = /MSIE [1-8]\b/.test(navigator.userAgent);
+var mac = /Mac/.test(navigator.platform);
+var phantom = /PhantomJS/.test(navigator.userAgent);
+var opera = /Opera\/\./.test(navigator.userAgent);
+var opera_version = opera && navigator.userAgent.match(/Version\/(\d+\.\d+)/);
+if (opera_version) opera_version = Number(opera_version);
+var opera_lt10 = opera && (!opera_version || opera_version < 10);
+
+namespace = "core_";
+
+test("core_fromTextArea", function() {
+ var te = document.getElementById("code");
+ te.value = "CONTENT";
+ var cm = CodeMirror.fromTextArea(te);
+ is(!te.offsetHeight);
+ eq(cm.getValue(), "CONTENT");
+ cm.setValue("foo\nbar");
+ eq(cm.getValue(), "foo\nbar");
+ cm.save();
+ is(/^foo\r?\nbar$/.test(te.value));
+ cm.setValue("xxx");
+ cm.toTextArea();
+ is(te.offsetHeight);
+ eq(te.value, "xxx");
+});
+
+testCM("getRange", function(cm) {
+ eq(cm.getLine(0), "1234");
+ eq(cm.getLine(1), "5678");
+ eq(cm.getLine(2), null);
+ eq(cm.getLine(-1), null);
+ eq(cm.getRange(Pos(0, 0), Pos(0, 3)), "123");
+ eq(cm.getRange(Pos(0, -1), Pos(0, 200)), "1234");
+ eq(cm.getRange(Pos(0, 2), Pos(1, 2)), "34\n56");
+ eq(cm.getRange(Pos(1, 2), Pos(100, 0)), "78");
+}, {value: "1234\n5678"});
+
+testCM("replaceRange", function(cm) {
+ eq(cm.getValue(), "");
+ cm.replaceRange("foo\n", Pos(0, 0));
+ eq(cm.getValue(), "foo\n");
+ cm.replaceRange("a\nb", Pos(0, 1));
+ eq(cm.getValue(), "fa\nboo\n");
+ eq(cm.lineCount(), 3);
+ cm.replaceRange("xyzzy", Pos(0, 0), Pos(1, 1));
+ eq(cm.getValue(), "xyzzyoo\n");
+ cm.replaceRange("abc", Pos(0, 0), Pos(10, 0));
+ eq(cm.getValue(), "abc");
+ eq(cm.lineCount(), 1);
+});
+
+testCM("selection", function(cm) {
+ cm.setSelection(Pos(0, 4), Pos(2, 2));
+ is(cm.somethingSelected());
+ eq(cm.getSelection(), "11\n222222\n33");
+ eqCursorPos(cm.getCursor(false), Pos(2, 2));
+ eqCursorPos(cm.getCursor(true), Pos(0, 4));
+ cm.setSelection(Pos(1, 0));
+ is(!cm.somethingSelected());
+ eq(cm.getSelection(), "");
+ eqCursorPos(cm.getCursor(true), Pos(1, 0));
+ cm.replaceSelection("abc", "around");
+ eq(cm.getSelection(), "abc");
+ eq(cm.getValue(), "111111\nabc222222\n333333");
+ cm.replaceSelection("def", "end");
+ eq(cm.getSelection(), "");
+ eqCursorPos(cm.getCursor(true), Pos(1, 3));
+ cm.setCursor(Pos(2, 1));
+ eqCursorPos(cm.getCursor(true), Pos(2, 1));
+ cm.setCursor(1, 2);
+ eqCursorPos(cm.getCursor(true), Pos(1, 2));
+}, {value: "111111\n222222\n333333"});
+
+testCM("extendSelection", function(cm) {
+ cm.setExtending(true);
+ addDoc(cm, 10, 10);
+ cm.setSelection(Pos(3, 5));
+ eqCursorPos(cm.getCursor("head"), Pos(3, 5));
+ eqCursorPos(cm.getCursor("anchor"), Pos(3, 5));
+ cm.setSelection(Pos(2, 5), Pos(5, 5));
+ eqCursorPos(cm.getCursor("head"), Pos(5, 5));
+ eqCursorPos(cm.getCursor("anchor"), Pos(2, 5));
+ eqCursorPos(cm.getCursor("start"), Pos(2, 5));
+ eqCursorPos(cm.getCursor("end"), Pos(5, 5));
+ cm.setSelection(Pos(5, 5), Pos(2, 5));
+ eqCursorPos(cm.getCursor("head"), Pos(2, 5));
+ eqCursorPos(cm.getCursor("anchor"), Pos(5, 5));
+ eqCursorPos(cm.getCursor("start"), Pos(2, 5));
+ eqCursorPos(cm.getCursor("end"), Pos(5, 5));
+ cm.extendSelection(Pos(3, 2));
+ eqCursorPos(cm.getCursor("head"), Pos(3, 2));
+ eqCursorPos(cm.getCursor("anchor"), Pos(5, 5));
+ cm.extendSelection(Pos(6, 2));
+ eqCursorPos(cm.getCursor("head"), Pos(6, 2));
+ eqCursorPos(cm.getCursor("anchor"), Pos(5, 5));
+ cm.extendSelection(Pos(6, 3), Pos(6, 4));
+ eqCursorPos(cm.getCursor("head"), Pos(6, 4));
+ eqCursorPos(cm.getCursor("anchor"), Pos(5, 5));
+ cm.extendSelection(Pos(0, 3), Pos(0, 4));
+ eqCursorPos(cm.getCursor("head"), Pos(0, 3));
+ eqCursorPos(cm.getCursor("anchor"), Pos(5, 5));
+ cm.extendSelection(Pos(4, 5), Pos(6, 5));
+ eqCursorPos(cm.getCursor("head"), Pos(6, 5));
+ eqCursorPos(cm.getCursor("anchor"), Pos(4, 5));
+ cm.setExtending(false);
+ cm.extendSelection(Pos(0, 3), Pos(0, 4));
+ eqCursorPos(cm.getCursor("head"), Pos(0, 3));
+ eqCursorPos(cm.getCursor("anchor"), Pos(0, 4));
+});
+
+testCM("lines", function(cm) {
+ eq(cm.getLine(0), "111111");
+ eq(cm.getLine(1), "222222");
+ eq(cm.getLine(-1), null);
+ cm.replaceRange("", Pos(1, 0), Pos(2, 0))
+ cm.replaceRange("abc", Pos(1, 0), Pos(1));
+ eq(cm.getValue(), "111111\nabc");
+}, {value: "111111\n222222\n333333"});
+
+testCM("indent", function(cm) {
+ cm.indentLine(1);
+ eq(cm.getLine(1), " blah();");
+ cm.setOption("indentUnit", 8);
+ cm.indentLine(1);
+ eq(cm.getLine(1), "\tblah();");
+ cm.setOption("indentUnit", 10);
+ cm.setOption("tabSize", 4);
+ cm.indentLine(1);
+ eq(cm.getLine(1), "\t\t blah();");
+}, {value: "if (x) {\nblah();\n}", indentUnit: 3, indentWithTabs: true, tabSize: 8});
+
+testCM("indentByNumber", function(cm) {
+ cm.indentLine(0, 2);
+ eq(cm.getLine(0), " foo");
+ cm.indentLine(0, -200);
+ eq(cm.getLine(0), "foo");
+ cm.setSelection(Pos(0, 0), Pos(1, 2));
+ cm.indentSelection(3);
+ eq(cm.getValue(), " foo\n bar\nbaz");
+}, {value: "foo\nbar\nbaz"});
+
+test("core_defaults", function() {
+ var defsCopy = {}, defs = CodeMirror.defaults;
+ for (var opt in defs) defsCopy[opt] = defs[opt];
+ defs.indentUnit = 5;
+ defs.value = "uu";
+ defs.indentWithTabs = true;
+ defs.tabindex = 55;
+ var place = document.getElementById("testground"), cm = CodeMirror(place);
+ try {
+ eq(cm.getOption("indentUnit"), 5);
+ cm.setOption("indentUnit", 10);
+ eq(defs.indentUnit, 5);
+ eq(cm.getValue(), "uu");
+ eq(cm.getOption("indentWithTabs"), true);
+ eq(cm.getInputField().tabIndex, 55);
+ }
+ finally {
+ for (var opt in defsCopy) defs[opt] = defsCopy[opt];
+ place.removeChild(cm.getWrapperElement());
+ }
+});
+
+testCM("lineInfo", function(cm) {
+ eq(cm.lineInfo(-1), null);
+ var mark = document.createElement("span");
+ var lh = cm.setGutterMarker(1, "FOO", mark);
+ var info = cm.lineInfo(1);
+ eq(info.text, "222222");
+ eq(info.gutterMarkers.FOO, mark);
+ eq(info.line, 1);
+ eq(cm.lineInfo(2).gutterMarkers, null);
+ cm.setGutterMarker(lh, "FOO", null);
+ eq(cm.lineInfo(1).gutterMarkers, null);
+ cm.setGutterMarker(1, "FOO", mark);
+ cm.setGutterMarker(0, "FOO", mark);
+ cm.clearGutter("FOO");
+ eq(cm.lineInfo(0).gutterMarkers, null);
+ eq(cm.lineInfo(1).gutterMarkers, null);
+}, {value: "111111\n222222\n333333"});
+
+testCM("coords", function(cm) {
+ cm.setSize(null, 100);
+ addDoc(cm, 32, 200);
+ var top = cm.charCoords(Pos(0, 0));
+ var bot = cm.charCoords(Pos(200, 30));
+ is(top.left < bot.left);
+ is(top.top < bot.top);
+ is(top.top < top.bottom);
+ cm.scrollTo(null, 100);
+ var top2 = cm.charCoords(Pos(0, 0));
+ is(top.top > top2.top);
+ eq(top.left, top2.left);
+});
+
+testCM("coordsChar", function(cm) {
+ addDoc(cm, 35, 70);
+ for (var i = 0; i < 2; ++i) {
+ var sys = i ? "local" : "page";
+ for (var ch = 0; ch <= 35; ch += 5) {
+ for (var line = 0; line < 70; line += 5) {
+ cm.setCursor(line, ch);
+ var coords = cm.charCoords(Pos(line, ch), sys);
+ var pos = cm.coordsChar({left: coords.left + 1, top: coords.top + 1}, sys);
+ eqCharPos(pos, Pos(line, ch));
+ }
+ }
+ }
+}, {lineNumbers: true});
+
+testCM("coordsCharBidi", function(cm) {
+ addDoc(cm, 35, 70);
+ // Put an rtl character into each line to trigger the bidi code path in coordsChar
+ cm.setValue(cm.getValue().replace(/\bx/g, 'و'))
+ for (var i = 0; i < 2; ++i) {
+ var sys = i ? "local" : "page";
+ for (var ch = 2; ch <= 35; ch += 5) {
+ for (var line = 0; line < 70; line += 5) {
+ cm.setCursor(line, ch);
+ var coords = cm.charCoords(Pos(line, ch), sys);
+ var pos = cm.coordsChar({left: coords.left + 1, top: coords.top + 1}, sys);
+ eqCharPos(pos, Pos(line, ch));
+ }
+ }
+ }
+}, {lineNumbers: true});
+
+testCM("badBidiOptimization", function(cm) {
+ var coords = cm.charCoords(Pos(0, 34))
+ eqCharPos(cm.coordsChar({left: coords.right, top: coords.top + 2}), Pos(0, 34))
+}, {value: "----------<p class=\"title\">هل يمكنك اختيار مستوى قسط التأمين الذي ترغب بدفعه؟</p>"})
+
+testCM("posFromIndex", function(cm) {
+ cm.setValue(
+ "This function should\n" +
+ "convert a zero based index\n" +
+ "to line and ch."
+ );
+
+ var examples = [
+ { index: -1, line: 0, ch: 0 }, // <- Tests clipping
+ { index: 0, line: 0, ch: 0 },
+ { index: 10, line: 0, ch: 10 },
+ { index: 39, line: 1, ch: 18 },
+ { index: 55, line: 2, ch: 7 },
+ { index: 63, line: 2, ch: 15 },
+ { index: 64, line: 2, ch: 15 } // <- Tests clipping
+ ];
+
+ for (var i = 0; i < examples.length; i++) {
+ var example = examples[i];
+ var pos = cm.posFromIndex(example.index);
+ eq(pos.line, example.line);
+ eq(pos.ch, example.ch);
+ if (example.index >= 0 && example.index < 64)
+ eq(cm.indexFromPos(pos), example.index);
+ }
+});
+
+testCM("undo", function(cm) {
+ cm.replaceRange("def", Pos(0, 0), Pos(0));
+ eq(cm.historySize().undo, 1);
+ cm.undo();
+ eq(cm.getValue(), "abc");
+ eq(cm.historySize().undo, 0);
+ eq(cm.historySize().redo, 1);
+ cm.redo();
+ eq(cm.getValue(), "def");
+ eq(cm.historySize().undo, 1);
+ eq(cm.historySize().redo, 0);
+ cm.setValue("1\n\n\n2");
+ cm.clearHistory();
+ eq(cm.historySize().undo, 0);
+ for (var i = 0; i < 20; ++i) {
+ cm.replaceRange("a", Pos(0, 0));
+ cm.replaceRange("b", Pos(3, 0));
+ }
+ eq(cm.historySize().undo, 40);
+ for (var i = 0; i < 40; ++i)
+ cm.undo();
+ eq(cm.historySize().redo, 40);
+ eq(cm.getValue(), "1\n\n\n2");
+}, {value: "abc"});
+
+testCM("undoDepth", function(cm) {
+ cm.replaceRange("d", Pos(0));
+ cm.replaceRange("e", Pos(0));
+ cm.replaceRange("f", Pos(0));
+ cm.undo(); cm.undo(); cm.undo();
+ eq(cm.getValue(), "abcd");
+}, {value: "abc", undoDepth: 4});
+
+testCM("undoDoesntClearValue", function(cm) {
+ cm.undo();
+ eq(cm.getValue(), "x");
+}, {value: "x"});
+
+testCM("undoMultiLine", function(cm) {
+ cm.operation(function() {
+ cm.replaceRange("x", Pos(0, 0));
+ cm.replaceRange("y", Pos(1, 0));
+ });
+ cm.undo();
+ eq(cm.getValue(), "abc\ndef\nghi");
+ cm.operation(function() {
+ cm.replaceRange("y", Pos(1, 0));
+ cm.replaceRange("x", Pos(0, 0));
+ });
+ cm.undo();
+ eq(cm.getValue(), "abc\ndef\nghi");
+ cm.operation(function() {
+ cm.replaceRange("y", Pos(2, 0));
+ cm.replaceRange("x", Pos(1, 0));
+ cm.replaceRange("z", Pos(2, 0));
+ });
+ cm.undo();
+ eq(cm.getValue(), "abc\ndef\nghi", 3);
+}, {value: "abc\ndef\nghi"});
+
+testCM("undoComposite", function(cm) {
+ cm.replaceRange("y", Pos(1));
+ cm.operation(function() {
+ cm.replaceRange("x", Pos(0));
+ cm.replaceRange("z", Pos(2));
+ });
+ eq(cm.getValue(), "ax\nby\ncz\n");
+ cm.undo();
+ eq(cm.getValue(), "a\nby\nc\n");
+ cm.undo();
+ eq(cm.getValue(), "a\nb\nc\n");
+ cm.redo(); cm.redo();
+ eq(cm.getValue(), "ax\nby\ncz\n");
+}, {value: "a\nb\nc\n"});
+
+testCM("undoSelection", function(cm) {
+ cm.setSelection(Pos(0, 2), Pos(0, 4));
+ cm.replaceSelection("");
+ cm.setCursor(Pos(1, 0));
+ cm.undo();
+ eqCursorPos(cm.getCursor(true), Pos(0, 2));
+ eqCursorPos(cm.getCursor(false), Pos(0, 4));
+ cm.setCursor(Pos(1, 0));
+ cm.redo();
+ eqCursorPos(cm.getCursor(true), Pos(0, 2));
+ eqCursorPos(cm.getCursor(false), Pos(0, 2));
+}, {value: "abcdefgh\n"});
+
+testCM("undoSelectionAsBefore", function(cm) {
+ cm.replaceSelection("abc", "around");
+ cm.undo();
+ cm.redo();
+ eq(cm.getSelection(), "abc");
+});
+
+testCM("selectionChangeConfusesHistory", function(cm) {
+ cm.replaceSelection("abc", null, "dontmerge");
+ cm.operation(function() {
+ cm.setCursor(Pos(0, 0));
+ cm.replaceSelection("abc", null, "dontmerge");
+ });
+ eq(cm.historySize().undo, 2);
+});
+
+testCM("markTextSingleLine", function(cm) {
+ forEach([{a: 0, b: 1, c: "", f: 2, t: 5},
+ {a: 0, b: 4, c: "", f: 0, t: 2},
+ {a: 1, b: 2, c: "x", f: 3, t: 6},
+ {a: 4, b: 5, c: "", f: 3, t: 5},
+ {a: 4, b: 5, c: "xx", f: 3, t: 7},
+ {a: 2, b: 5, c: "", f: 2, t: 3},
+ {a: 2, b: 5, c: "abcd", f: 6, t: 7},
+ {a: 2, b: 6, c: "x", f: null, t: null},
+ {a: 3, b: 6, c: "", f: null, t: null},
+ {a: 0, b: 9, c: "hallo", f: null, t: null},
+ {a: 4, b: 6, c: "x", f: 3, t: 4},
+ {a: 4, b: 8, c: "", f: 3, t: 4},
+ {a: 6, b: 6, c: "a", f: 3, t: 6},
+ {a: 8, b: 9, c: "", f: 3, t: 6}], function(test) {
+ cm.setValue("1234567890");
+ var r = cm.markText(Pos(0, 3), Pos(0, 6), {className: "foo"});
+ cm.replaceRange(test.c, Pos(0, test.a), Pos(0, test.b));
+ var f = r.find();
+ eq(f && f.from.ch, test.f); eq(f && f.to.ch, test.t);
+ });
+});
+
+testCM("markTextMultiLine", function(cm) {
+ function p(v) { return v && Pos(v[0], v[1]); }
+ forEach([{a: [0, 0], b: [0, 5], c: "", f: [0, 0], t: [2, 5]},
+ {a: [0, 0], b: [0, 5], c: "foo\n", f: [1, 0], t: [3, 5]},
+ {a: [0, 1], b: [0, 10], c: "", f: [0, 1], t: [2, 5]},
+ {a: [0, 5], b: [0, 6], c: "x", f: [0, 6], t: [2, 5]},
+ {a: [0, 0], b: [1, 0], c: "", f: [0, 0], t: [1, 5]},
+ {a: [0, 6], b: [2, 4], c: "", f: [0, 5], t: [0, 7]},
+ {a: [0, 6], b: [2, 4], c: "aa", f: [0, 5], t: [0, 9]},
+ {a: [1, 2], b: [1, 8], c: "", f: [0, 5], t: [2, 5]},
+ {a: [0, 5], b: [2, 5], c: "xx", f: null, t: null},
+ {a: [0, 0], b: [2, 10], c: "x", f: null, t: null},
+ {a: [1, 5], b: [2, 5], c: "", f: [0, 5], t: [1, 5]},
+ {a: [2, 0], b: [2, 3], c: "", f: [0, 5], t: [2, 2]},
+ {a: [2, 5], b: [3, 0], c: "a\nb", f: [0, 5], t: [2, 5]},
+ {a: [2, 3], b: [3, 0], c: "x", f: [0, 5], t: [2, 3]},
+ {a: [1, 1], b: [1, 9], c: "1\n2\n3", f: [0, 5], t: [4, 5]}], function(test) {
+ cm.setValue("aaaaaaaaaa\nbbbbbbbbbb\ncccccccccc\ndddddddd\n");
+ var r = cm.markText(Pos(0, 5), Pos(2, 5),
+ {className: "CodeMirror-matchingbracket"});
+ cm.replaceRange(test.c, p(test.a), p(test.b));
+ var f = r.find();
+ eqCursorPos(f && f.from, p(test.f)); eqCursorPos(f && f.to, p(test.t));
+ });
+});
+
+testCM("markTextUndo", function(cm) {
+ var marker1, marker2, bookmark;
+ marker1 = cm.markText(Pos(0, 1), Pos(0, 3),
+ {className: "CodeMirror-matchingbracket"});
+ marker2 = cm.markText(Pos(0, 0), Pos(2, 1),
+ {className: "CodeMirror-matchingbracket"});
+ bookmark = cm.setBookmark(Pos(1, 5));
+ cm.operation(function(){
+ cm.replaceRange("foo", Pos(0, 2));
+ cm.replaceRange("bar\nbaz\nbug\n", Pos(2, 0), Pos(3, 0));
+ });
+ var v1 = cm.getValue();
+ cm.setValue("");
+ eq(marker1.find(), null); eq(marker2.find(), null); eq(bookmark.find(), null);
+ cm.undo();
+ eqCursorPos(bookmark.find(), Pos(1, 5), "still there");
+ cm.undo();
+ var m1Pos = marker1.find(), m2Pos = marker2.find();
+ eqCursorPos(m1Pos.from, Pos(0, 1)); eqCursorPos(m1Pos.to, Pos(0, 3));
+ eqCursorPos(m2Pos.from, Pos(0, 0)); eqCursorPos(m2Pos.to, Pos(2, 1));
+ eqCursorPos(bookmark.find(), Pos(1, 5));
+ cm.redo(); cm.redo();
+ eq(bookmark.find(), null);
+ cm.undo();
+ eqCursorPos(bookmark.find(), Pos(1, 5));
+ eq(cm.getValue(), v1);
+}, {value: "1234\n56789\n00\n"});
+
+testCM("markTextStayGone", function(cm) {
+ var m1 = cm.markText(Pos(0, 0), Pos(0, 1));
+ cm.replaceRange("hi", Pos(0, 2));
+ m1.clear();
+ cm.undo();
+ eq(m1.find(), null);
+}, {value: "hello"});
+
+testCM("markTextAllowEmpty", function(cm) {
+ var m1 = cm.markText(Pos(0, 1), Pos(0, 2), {clearWhenEmpty: false});
+ is(m1.find());
+ cm.replaceRange("x", Pos(0, 0));
+ is(m1.find());
+ cm.replaceRange("y", Pos(0, 2));
+ is(m1.find());
+ cm.replaceRange("z", Pos(0, 3), Pos(0, 4));
+ is(!m1.find());
+ var m2 = cm.markText(Pos(0, 1), Pos(0, 2), {clearWhenEmpty: false,
+ inclusiveLeft: true,
+ inclusiveRight: true});
+ cm.replaceRange("q", Pos(0, 1), Pos(0, 2));
+ is(m2.find());
+ cm.replaceRange("", Pos(0, 0), Pos(0, 3));
+ is(!m2.find());
+ var m3 = cm.markText(Pos(0, 1), Pos(0, 1), {clearWhenEmpty: false});
+ cm.replaceRange("a", Pos(0, 3));
+ is(m3.find());
+ cm.replaceRange("b", Pos(0, 1));
+ is(!m3.find());
+}, {value: "abcde"});
+
+testCM("markTextStacked", function(cm) {
+ var m1 = cm.markText(Pos(0, 0), Pos(0, 0), {clearWhenEmpty: false});
+ var m2 = cm.markText(Pos(0, 0), Pos(0, 0), {clearWhenEmpty: false});
+ cm.replaceRange("B", Pos(0, 1));
+ is(m1.find() && m2.find());
+}, {value: "A"});
+
+testCM("undoPreservesNewMarks", function(cm) {
+ cm.markText(Pos(0, 3), Pos(0, 4));
+ cm.markText(Pos(1, 1), Pos(1, 3));
+ cm.replaceRange("", Pos(0, 3), Pos(3, 1));
+ var mBefore = cm.markText(Pos(0, 0), Pos(0, 1));
+ var mAfter = cm.markText(Pos(0, 5), Pos(0, 6));
+ var mAround = cm.markText(Pos(0, 2), Pos(0, 4));
+ cm.undo();
+ eqCursorPos(mBefore.find().from, Pos(0, 0));
+ eqCursorPos(mBefore.find().to, Pos(0, 1));
+ eqCursorPos(mAfter.find().from, Pos(3, 3));
+ eqCursorPos(mAfter.find().to, Pos(3, 4));
+ eqCursorPos(mAround.find().from, Pos(0, 2));
+ eqCursorPos(mAround.find().to, Pos(3, 2));
+ var found = cm.findMarksAt(Pos(2, 2));
+ eq(found.length, 1);
+ eq(found[0], mAround);
+}, {value: "aaaa\nbbbb\ncccc\ndddd"});
+
+testCM("markClearBetween", function(cm) {
+ cm.setValue("aaa\nbbb\nccc\nddd\n");
+ cm.markText(Pos(0, 0), Pos(2));
+ cm.replaceRange("aaa\nbbb\nccc", Pos(0, 0), Pos(2));
+ eq(cm.findMarksAt(Pos(1, 1)).length, 0);
+});
+
+testCM("findMarksMiddle", function(cm) {
+ var mark = cm.markText(Pos(1, 1), Pos(3, 1));
+ var found = cm.findMarks(Pos(2, 1), Pos(2, 2));
+ eq(found.length, 1);
+ eq(found[0], mark);
+}, {value: "line 0\nline 1\nline 2\nline 3"});
+
+testCM("deleteSpanCollapsedInclusiveLeft", function(cm) {
+ var from = Pos(1, 0), to = Pos(1, 1);
+ var m = cm.markText(from, to, {collapsed: true, inclusiveLeft: true});
+ // Delete collapsed span.
+ cm.replaceRange("", from, to);
+}, {value: "abc\nX\ndef"});
+
+testCM("markTextCSS", function(cm) {
+ function present() {
+ var spans = cm.display.lineDiv.getElementsByTagName("span");
+ for (var i = 0; i < spans.length; i++)
+ if (spans[i].style.color && spans[i].textContent == "cdef") return true;
+ }
+ var m = cm.markText(Pos(0, 2), Pos(0, 6), {css: "color: cyan"});
+ is(present());
+ m.clear();
+ is(!present());
+}, {value: "abcdefgh"});
+
+testCM("markTextWithAttributes", function(cm) {
+ function present() {
+ var spans = cm.display.lineDiv.getElementsByTagName("span");
+ for (var i = 0; i < spans.length; i++)
+ if (spans[i].getAttribute("label") == "label" && spans[i].textContent == "cdef") return true;
+ }
+ var m = cm.markText(Pos(0, 2), Pos(0, 6), {attributes: {label: "label"}});
+ is(present());
+ m.clear();
+ is(!present());
+}, {value: "abcdefgh"});
+
+testCM("bookmark", function(cm) {
+ function p(v) { return v && Pos(v[0], v[1]); }
+ forEach([{a: [1, 0], b: [1, 1], c: "", d: [1, 4]},
+ {a: [1, 1], b: [1, 1], c: "xx", d: [1, 7]},
+ {a: [1, 4], b: [1, 5], c: "ab", d: [1, 6]},
+ {a: [1, 4], b: [1, 6], c: "", d: null},
+ {a: [1, 5], b: [1, 6], c: "abc", d: [1, 5]},
+ {a: [1, 6], b: [1, 8], c: "", d: [1, 5]},
+ {a: [1, 4], b: [1, 4], c: "\n\n", d: [3, 1]},
+ {bm: [1, 9], a: [1, 1], b: [1, 1], c: "\n", d: [2, 8]}], function(test) {
+ cm.setValue("1234567890\n1234567890\n1234567890");
+ var b = cm.setBookmark(p(test.bm) || Pos(1, 5));
+ cm.replaceRange(test.c, p(test.a), p(test.b));
+ eqCursorPos(b.find(), p(test.d));
+ });
+});
+
+testCM("bookmarkInsertLeft", function(cm) {
+ var br = cm.setBookmark(Pos(0, 2), {insertLeft: false});
+ var bl = cm.setBookmark(Pos(0, 2), {insertLeft: true});
+ cm.setCursor(Pos(0, 2));
+ cm.replaceSelection("hi");
+ eqCursorPos(br.find(), Pos(0, 2));
+ eqCursorPos(bl.find(), Pos(0, 4));
+ cm.replaceRange("", Pos(0, 4), Pos(0, 5));
+ cm.replaceRange("", Pos(0, 2), Pos(0, 4));
+ cm.replaceRange("", Pos(0, 1), Pos(0, 2));
+ // Verify that deleting next to bookmarks doesn't kill them
+ eqCursorPos(br.find(), Pos(0, 1));
+ eqCursorPos(bl.find(), Pos(0, 1));
+}, {value: "abcdef"});
+
+testCM("bookmarkCursor", function(cm) {
+ var pos01 = cm.cursorCoords(Pos(0, 1)), pos11 = cm.cursorCoords(Pos(1, 1)),
+ pos20 = cm.cursorCoords(Pos(2, 0)), pos30 = cm.cursorCoords(Pos(3, 0)),
+ pos41 = cm.cursorCoords(Pos(4, 1));
+ cm.setBookmark(Pos(0, 1), {widget: document.createTextNode("←"), insertLeft: true});
+ cm.setBookmark(Pos(2, 0), {widget: document.createTextNode("←"), insertLeft: true});
+ cm.setBookmark(Pos(1, 1), {widget: document.createTextNode("→")});
+ cm.setBookmark(Pos(3, 0), {widget: document.createTextNode("→")});
+ var new01 = cm.cursorCoords(Pos(0, 1)), new11 = cm.cursorCoords(Pos(1, 1)),
+ new20 = cm.cursorCoords(Pos(2, 0)), new30 = cm.cursorCoords(Pos(3, 0));
+ near(new01.left, pos01.left, 1);
+ near(new01.top, pos01.top, 1);
+ is(new11.left > pos11.left, "at right, middle of line");
+ near(new11.top == pos11.top, 1);
+ near(new20.left, pos20.left, 1);
+ near(new20.top, pos20.top, 1);
+ is(new30.left > pos30.left, "at right, empty line");
+ near(new30.top, pos30, 1);
+ cm.setBookmark(Pos(4, 0), {widget: document.createTextNode("→")});
+ is(cm.cursorCoords(Pos(4, 1)).left > pos41.left, "single-char bug");
+}, {value: "foo\nbar\n\n\nx\ny"});
+
+testCM("multiBookmarkCursor", function(cm) {
+ if (phantom) return;
+ var ms = [], m;
+ function add(insertLeft) {
+ for (var i = 0; i < 3; ++i) {
+ var node = document.createElement("span");
+ node.innerHTML = "X";
+ ms.push(cm.setBookmark(Pos(0, 1), {widget: node, insertLeft: insertLeft}));
+ }
+ }
+ var base1 = cm.cursorCoords(Pos(0, 1)).left, base4 = cm.cursorCoords(Pos(0, 4)).left;
+ add(true);
+ near(base1, cm.cursorCoords(Pos(0, 1)).left, 1);
+ while (m = ms.pop()) m.clear();
+ add(false);
+ near(base4, cm.cursorCoords(Pos(0, 1)).left, 1);
+}, {value: "abcdefg"});
+
+testCM("getAllMarks", function(cm) {
+ addDoc(cm, 10, 10);
+ var m1 = cm.setBookmark(Pos(0, 2));
+ var m2 = cm.markText(Pos(0, 2), Pos(3, 2));
+ var m3 = cm.markText(Pos(1, 2), Pos(1, 8));
+ var m4 = cm.markText(Pos(8, 0), Pos(9, 0));
+ eq(cm.getAllMarks().length, 4);
+ m1.clear();
+ m3.clear();
+ eq(cm.getAllMarks().length, 2);
+});
+
+testCM("setValueClears", function(cm) {
+ cm.addLineClass(0, "wrap", "foo");
+ var mark = cm.markText(Pos(0, 0), Pos(1, 1), {inclusiveLeft: true, inclusiveRight: true});
+ cm.setValue("foo");
+ is(!cm.lineInfo(0).wrapClass);
+ is(!mark.find());
+}, {value: "a\nb"});
+
+testCM("bug577", function(cm) {
+ cm.setValue("a\nb");
+ cm.clearHistory();
+ cm.setValue("fooooo");
+ cm.undo();
+});
+
+testCM("scrollSnap", function(cm) {
+ cm.setSize(100, 100);
+ addDoc(cm, 200, 200);
+ cm.setCursor(Pos(100, 180));
+ var info = cm.getScrollInfo();
+ is(info.left > 0 && info.top > 0);
+ cm.setCursor(Pos(0, 0));
+ info = cm.getScrollInfo();
+ is(info.left == 0 && info.top == 0, "scrolled clean to top");
+ cm.setCursor(Pos(100, 180));
+ cm.setCursor(Pos(199, 0));
+ info = cm.getScrollInfo();
+ is(info.left == 0 && info.top + 2 > info.height - cm.getScrollerElement().clientHeight, "scrolled clean to bottom");
+});
+
+testCM("scrollIntoView", function(cm) {
+ if (phantom) return;
+ function test(line, ch, msg) {
+ var pos = Pos(line, ch);
+ cm.scrollIntoView(pos);
+ var outer = cm.getWrapperElement().getBoundingClientRect();
+ var box = cm.charCoords(pos, "window");
+ is(box.left >= outer.left, msg + " (left)");
+ is(box.right <= outer.right, msg + " (right)");
+ is(box.top >= outer.top, msg + " (top)");
+ is(box.bottom <= outer.bottom, msg + " (bottom)");
+ }
+ addDoc(cm, 200, 200);
+ test(199, 199, "bottom right");
+ test(0, 0, "top left");
+ test(100, 100, "center");
+ test(199, 0, "bottom left");
+ test(0, 199, "top right");
+ test(100, 100, "center again");
+});
+
+testCM("scrollBackAndForth", function(cm) {
+ addDoc(cm, 1, 200);
+ cm.operation(function() {
+ cm.scrollIntoView(Pos(199, 0));
+ cm.scrollIntoView(Pos(4, 0));
+ });
+ is(cm.getScrollInfo().top > 0);
+});
+
+testCM("selectAllNoScroll", function(cm) {
+ addDoc(cm, 1, 200);
+ cm.execCommand("selectAll");
+ eq(cm.getScrollInfo().top, 0);
+ cm.setCursor(199);
+ cm.execCommand("selectAll");
+ is(cm.getScrollInfo().top > 0);
+});
+
+testCM("selectionPos", function(cm) {
+ if (phantom || cm.getOption("inputStyle") != "textarea") return;
+ cm.setSize(100, 100);
+ addDoc(cm, 200, 100);
+ cm.setSelection(Pos(1, 100), Pos(98, 100));
+ var lineWidth = cm.charCoords(Pos(0, 200), "local").left;
+ var lineHeight = (cm.charCoords(Pos(99)).top - cm.charCoords(Pos(0)).top) / 100;
+ cm.scrollTo(0, 0);
+ var selElt = byClassName(cm.getWrapperElement(), "CodeMirror-selected");
+ var outer = cm.getWrapperElement().getBoundingClientRect();
+ var sawMiddle, sawTop, sawBottom;
+ for (var i = 0, e = selElt.length; i < e; ++i) {
+ var box = selElt[i].getBoundingClientRect();
+ var atLeft = box.left - outer.left < 30;
+ var width = box.right - box.left;
+ var atRight = box.right - outer.left > .8 * lineWidth;
+ if (atLeft && atRight) {
+ sawMiddle = true;
+ is(box.bottom - box.top > 90 * lineHeight, "middle high");
+ is(width > .9 * lineWidth, "middle wide");
+ } else {
+ is(width > .4 * lineWidth, "top/bot wide enough");
+ is(width < .6 * lineWidth, "top/bot slim enough");
+ if (atLeft) {
+ sawBottom = true;
+ is(box.top - outer.top > 96 * lineHeight, "bot below");
+ } else if (atRight) {
+ sawTop = true;
+ is(box.top - outer.top < 2.1 * lineHeight, "top above");
+ }
+ }
+ }
+ is(sawTop && sawBottom && sawMiddle, "all parts");
+}, null);
+
+testCM("restoreHistory", function(cm) {
+ cm.setValue("abc\ndef");
+ cm.replaceRange("hello", Pos(1, 0), Pos(1));
+ cm.replaceRange("goop", Pos(0, 0), Pos(0));
+ cm.undo();
+ var storedVal = cm.getValue(), storedHist = cm.getHistory();
+ if (window.JSON) storedHist = JSON.parse(JSON.stringify(storedHist));
+ eq(storedVal, "abc\nhello");
+ cm.setValue("");
+ cm.clearHistory();
+ eq(cm.historySize().undo, 0);
+ cm.setValue(storedVal);
+ cm.setHistory(storedHist);
+ cm.redo();
+ eq(cm.getValue(), "goop\nhello");
+ cm.undo(); cm.undo();
+ eq(cm.getValue(), "abc\ndef");
+});
+
+testCM("doubleScrollbar", function(cm) {
+ var dummy = document.body.appendChild(document.createElement("p"));
+ dummy.style.cssText = "height: 50px; overflow: scroll; width: 50px";
+ var scrollbarWidth = dummy.offsetWidth + 1 - dummy.clientWidth;
+ document.body.removeChild(dummy);
+ if (scrollbarWidth < 2) return;
+ cm.setSize(null, 100);
+ addDoc(cm, 1, 300);
+ var wrap = cm.getWrapperElement();
+ is(wrap.offsetWidth - byClassName(wrap, "CodeMirror-lines")[0].offsetWidth <= scrollbarWidth * 1.5);
+});
+
+testCM("weirdLinebreaks", function(cm) {
+ cm.setValue("foo\nbar\rbaz\r\nquux\n\rplop");
+ is(cm.getValue(), "foo\nbar\nbaz\nquux\n\nplop");
+ is(cm.lineCount(), 6);
+ cm.setValue("\n\n");
+ is(cm.lineCount(), 3);
+});
+
+testCM("setSize", function(cm) {
+ cm.setSize(100, 100);
+ var wrap = cm.getWrapperElement();
+ is(wrap.offsetWidth, 100);
+ is(wrap.offsetHeight, 100);
+ cm.setSize("100%", "3em");
+ is(wrap.style.width, "100%");
+ is(wrap.style.height, "3em");
+ cm.setSize(null, 40);
+ is(wrap.style.width, "100%");
+ is(wrap.style.height, "40px");
+});
+
+function foldLines(cm, start, end, autoClear) {
+ return cm.markText(Pos(start, 0), Pos(end - 1), {
+ inclusiveLeft: true,
+ inclusiveRight: true,
+ collapsed: true,
+ clearOnEnter: autoClear
+ });
+}
+
+testCM("collapsedLines", function(cm) {
+ addDoc(cm, 4, 10);
+ var range = foldLines(cm, 4, 5), cleared = 0;
+ CodeMirror.on(range, "clear", function() {cleared++;});
+ cm.setCursor(Pos(3, 0));
+ CodeMirror.commands.goLineDown(cm);
+ eqCharPos(cm.getCursor(), Pos(5, 0));
+ cm.replaceRange("abcdefg", Pos(3, 0), Pos(3));
+ cm.setCursor(Pos(3, 6));
+ CodeMirror.commands.goLineDown(cm);
+ eqCharPos(cm.getCursor(), Pos(5, 4));
+ cm.replaceRange("ab", Pos(3, 0), Pos(3));
+ cm.setCursor(Pos(3, 2));
+ CodeMirror.commands.goLineDown(cm);
+ eqCharPos(cm.getCursor(), Pos(5, 2));
+ cm.operation(function() {range.clear(); range.clear();});
+ eq(cleared, 1);
+});
+
+testCM("collapsedRangeCoordsChar", function(cm) {
+ var pos_1_3 = cm.charCoords(Pos(1, 3));
+ pos_1_3.left += 2; pos_1_3.top += 2;
+ var opts = {collapsed: true, inclusiveLeft: true, inclusiveRight: true};
+ var m1 = cm.markText(Pos(0, 0), Pos(2, 0), opts);
+ eqCharPos(cm.coordsChar(pos_1_3), Pos(3, 3));
+ m1.clear();
+ var m1 = cm.markText(Pos(0, 0), Pos(1, 1), {collapsed: true, inclusiveLeft: true});
+ var m2 = cm.markText(Pos(1, 1), Pos(2, 0), {collapsed: true, inclusiveRight: true});
+ eqCharPos(cm.coordsChar(pos_1_3), Pos(3, 3));
+ m1.clear(); m2.clear();
+ var m1 = cm.markText(Pos(0, 0), Pos(1, 6), opts);
+ eqCharPos(cm.coordsChar(pos_1_3), Pos(3, 3));
+}, {value: "123456\nabcdef\nghijkl\nmnopqr\n"});
+
+testCM("collapsedRangeBetweenLinesSelected", function(cm) {
+ if (cm.getOption("inputStyle") != "textarea") return;
+ var widget = document.createElement("span");
+ widget.textContent = "\u2194";
+ cm.markText(Pos(0, 3), Pos(1, 0), {replacedWith: widget});
+ cm.setSelection(Pos(0, 3), Pos(1, 0));
+ var selElts = byClassName(cm.getWrapperElement(), "CodeMirror-selected");
+ for (var i = 0, w = 0; i < selElts.length; i++)
+ w += selElts[i].offsetWidth;
+ is(w > 0);
+}, {value: "one\ntwo"});
+
+testCM("randomCollapsedRanges", function(cm) {
+ addDoc(cm, 20, 500);
+ cm.operation(function() {
+ for (var i = 0; i < 200; i++) {
+ var start = Pos(Math.floor(Math.random() * 500), Math.floor(Math.random() * 20));
+ if (i % 4)
+ try { cm.markText(start, Pos(start.line + 2, 1), {collapsed: true}); }
+ catch(e) { if (!/overlapping/.test(String(e))) throw e; }
+ else
+ cm.markText(start, Pos(start.line, start.ch + 4), {"className": "foo"});
+ }
+ });
+});
+
+testCM("hiddenLinesAutoUnfold", function(cm) {
+ var range = foldLines(cm, 1, 3, true), cleared = 0;
+ CodeMirror.on(range, "clear", function() {cleared++;});
+ cm.setCursor(Pos(3, 0));
+ eq(cleared, 0);
+ cm.execCommand("goCharLeft");
+ eq(cleared, 1);
+ range = foldLines(cm, 1, 3, true);
+ CodeMirror.on(range, "clear", function() {cleared++;});
+ eqCursorPos(cm.getCursor(), Pos(3, 0));
+ cm.setCursor(Pos(0, 3));
+ cm.execCommand("goCharRight");
+ eq(cleared, 2);
+}, {value: "abc\ndef\nghi\njkl"});
+
+testCM("hiddenLinesSelectAll", function(cm) { // Issue #484
+ addDoc(cm, 4, 20);
+ foldLines(cm, 0, 10);
+ foldLines(cm, 11, 20);
+ CodeMirror.commands.selectAll(cm);
+ eqCursorPos(cm.getCursor(true), Pos(10, 0));
+ eqCursorPos(cm.getCursor(false), Pos(10, 4));
+});
+
+testCM("clickFold", function(cm) { // Issue #5392
+ cm.setValue("foo { bar }")
+ var widget = document.createElement("span")
+ widget.textContent = "<>"
+ cm.markText(Pos(0, 5), Pos(0, 10), {replacedWith: widget})
+ var after = cm.charCoords(Pos(0, 10))
+ var foundOn = cm.coordsChar({left: after.left - 1, top: after.top + 4})
+ is(foundOn.ch <= 5 || foundOn.ch >= 10, "Position is not inside the folded range")
+})
+
+testCM("everythingFolded", function(cm) {
+ addDoc(cm, 2, 2);
+ function enterPress() {
+ cm.triggerOnKeyDown({type: "keydown", keyCode: 13, preventDefault: function(){}, stopPropagation: function(){}});
+ }
+ var fold = foldLines(cm, 0, 2);
+ enterPress();
+ eq(cm.getValue(), "xx\nxx");
+ fold.clear();
+ fold = foldLines(cm, 0, 2, true);
+ eq(fold.find(), null);
+ enterPress();
+ eq(cm.getValue(), "\nxx\nxx");
+});
+
+testCM("structuredFold", function(cm) {
+ if (phantom) return;
+ addDoc(cm, 4, 8);
+ var range = cm.markText(Pos(1, 2), Pos(6, 2), {
+ replacedWith: document.createTextNode("Q")
+ });
+ cm.setCursor(0, 3);
+ CodeMirror.commands.goLineDown(cm);
+ eqCharPos(cm.getCursor(), Pos(6, 2));
+ CodeMirror.commands.goCharLeft(cm);
+ eqCharPos(cm.getCursor(), Pos(1, 2));
+ CodeMirror.commands.delCharAfter(cm);
+ eq(cm.getValue(), "xxxx\nxxxx\nxxxx");
+ addDoc(cm, 4, 8);
+ range = cm.markText(Pos(1, 2), Pos(6, 2), {
+ replacedWith: document.createTextNode("M"),
+ clearOnEnter: true
+ });
+ var cleared = 0;
+ CodeMirror.on(range, "clear", function(){++cleared;});
+ cm.setCursor(0, 3);
+ CodeMirror.commands.goLineDown(cm);
+ eqCharPos(cm.getCursor(), Pos(6, 2));
+ CodeMirror.commands.goCharLeft(cm);
+ eqCharPos(cm.getCursor(), Pos(6, 1));
+ eq(cleared, 1);
+ range.clear();
+ eq(cleared, 1);
+ range = cm.markText(Pos(1, 2), Pos(6, 2), {
+ replacedWith: document.createTextNode("Q"),
+ clearOnEnter: true
+ });
+ range.clear();
+ cm.setCursor(1, 2);
+ CodeMirror.commands.goCharRight(cm);
+ eqCharPos(cm.getCursor(), Pos(1, 3));
+ range = cm.markText(Pos(2, 0), Pos(4, 4), {
+ replacedWith: document.createTextNode("M")
+ });
+ cm.setCursor(1, 0);
+ CodeMirror.commands.goLineDown(cm);
+ eqCharPos(cm.getCursor(), Pos(2, 0));
+}, null);
+
+testCM("nestedFold", function(cm) {
+ addDoc(cm, 10, 3);
+ function fold(ll, cl, lr, cr) {
+ return cm.markText(Pos(ll, cl), Pos(lr, cr), {collapsed: true});
+ }
+ var inner1 = fold(0, 6, 1, 3), inner2 = fold(0, 2, 1, 8), outer = fold(0, 1, 2, 3), inner0 = fold(0, 5, 0, 6);
+ cm.setCursor(0, 1);
+ CodeMirror.commands.goCharRight(cm);
+ eqCursorPos(cm.getCursor(), Pos(2, 3));
+ inner0.clear();
+ CodeMirror.commands.goCharLeft(cm);
+ eqCursorPos(cm.getCursor(), Pos(0, 1));
+ outer.clear();
+ CodeMirror.commands.goCharRight(cm);
+ eqCursorPos(cm.getCursor(), Pos(0, 2, "before"));
+ CodeMirror.commands.goCharRight(cm);
+ eqCursorPos(cm.getCursor(), Pos(1, 8));
+ inner2.clear();
+ CodeMirror.commands.goCharLeft(cm);
+ eqCursorPos(cm.getCursor(), Pos(1, 7, "after"));
+ cm.setCursor(0, 5);
+ CodeMirror.commands.goCharRight(cm);
+ eqCursorPos(cm.getCursor(), Pos(0, 6, "before"));
+ CodeMirror.commands.goCharRight(cm);
+ eqCursorPos(cm.getCursor(), Pos(1, 3));
+});
+
+testCM("badNestedFold", function(cm) {
+ addDoc(cm, 4, 4);
+ cm.markText(Pos(0, 2), Pos(3, 2), {collapsed: true});
+ var caught;
+ try {cm.markText(Pos(0, 1), Pos(0, 3), {collapsed: true});}
+ catch(e) {caught = e;}
+ is(caught instanceof Error, "no error");
+ is(/overlap/i.test(caught.message), "wrong error");
+});
+
+testCM("nestedFoldOnSide", function(cm) {
+ var m1 = cm.markText(Pos(0, 1), Pos(2, 1), {collapsed: true, inclusiveRight: true});
+ var m2 = cm.markText(Pos(0, 1), Pos(0, 2), {collapsed: true});
+ cm.markText(Pos(0, 1), Pos(0, 2), {collapsed: true}).clear();
+ try { cm.markText(Pos(0, 1), Pos(0, 2), {collapsed: true, inclusiveLeft: true}); }
+ catch(e) { var caught = e; }
+ is(caught && /overlap/i.test(caught.message));
+ var m3 = cm.markText(Pos(2, 0), Pos(2, 1), {collapsed: true});
+ var m4 = cm.markText(Pos(2, 0), Pos(2, 1), {collapse: true, inclusiveRight: true});
+ m1.clear(); m4.clear();
+ m1 = cm.markText(Pos(0, 1), Pos(2, 1), {collapsed: true});
+ cm.markText(Pos(2, 0), Pos(2, 1), {collapsed: true}).clear();
+ try { cm.markText(Pos(2, 0), Pos(2, 1), {collapsed: true, inclusiveRight: true}); }
+ catch(e) { var caught = e; }
+ is(caught && /overlap/i.test(caught.message));
+}, {value: "ab\ncd\ef"});
+
+testCM("editInFold", function(cm) {
+ addDoc(cm, 4, 6);
+ var m = cm.markText(Pos(1, 2), Pos(3, 2), {collapsed: true});
+ cm.replaceRange("", Pos(0, 0), Pos(1, 3));
+ cm.replaceRange("", Pos(2, 1), Pos(3, 3));
+ cm.replaceRange("a\nb\nc\nd", Pos(0, 1), Pos(1, 0));
+ cm.cursorCoords(Pos(0, 0));
+});
+
+testCM("wrappingInlineWidget", function(cm) {
+ cm.setSize("11em");
+ var w = document.createElement("span");
+ w.style.color = "red";
+ w.innerHTML = "one two three four";
+ cm.markText(Pos(0, 6), Pos(0, 9), {replacedWith: w});
+ var cur0 = cm.cursorCoords(Pos(0, 0)), cur1 = cm.cursorCoords(Pos(0, 10));
+ is(cur0.top < cur1.top);
+ is(cur0.bottom < cur1.bottom);
+ var curL = cm.cursorCoords(Pos(0, 6)), curR = cm.cursorCoords(Pos(0, 9));
+ eq(curL.top, cur0.top);
+ eq(curL.bottom, cur0.bottom);
+ eq(curR.top, cur1.top);
+ eq(curR.bottom, cur1.bottom);
+ cm.replaceRange("", Pos(0, 9), Pos(0));
+ curR = cm.cursorCoords(Pos(0, 9));
+ if (phantom) return;
+ eq(curR.top, cur1.top);
+ eq(curR.bottom, cur1.bottom);
+}, {value: "1 2 3 xxx 4", lineWrapping: true});
+
+testCM("showEmptyWidgetSpan", function(cm) {
+ var marker = cm.markText(Pos(0, 2), Pos(0, 2), {
+ clearWhenEmpty: false,
+ replacedWith: document.createTextNode("X")
+ });
+ var text = cm.display.view[0].text;
+ eq(text.textContent || text.innerText, "abXc");
+}, {value: "abc"});
+
+testCM("changedInlineWidget", function(cm) {
+ cm.setSize("10em");
+ var w = document.createElement("span");
+ w.innerHTML = "x";
+ var m = cm.markText(Pos(0, 4), Pos(0, 5), {replacedWith: w});
+ w.innerHTML = "and now the widget is really really long all of a sudden and a scrollbar is needed";
+ m.changed();
+ var hScroll = byClassName(cm.getWrapperElement(), "CodeMirror-hscrollbar")[0];
+ is(hScroll.scrollWidth > hScroll.clientWidth);
+}, {value: "hello there"});
+
+testCM("changedBookmark", function(cm) {
+ cm.setSize("10em");
+ var w = document.createElement("span");
+ w.innerHTML = "x";
+ var m = cm.setBookmark(Pos(0, 4), {widget: w});
+ w.innerHTML = "and now the widget is really really long all of a sudden and a scrollbar is needed";
+ m.changed();
+ var hScroll = byClassName(cm.getWrapperElement(), "CodeMirror-hscrollbar")[0];
+ is(hScroll.scrollWidth > hScroll.clientWidth);
+}, {value: "abcdefg"});
+
+testCM("inlineWidget", function(cm) {
+ var w = cm.setBookmark(Pos(0, 2), {widget: document.createTextNode("uu")});
+ cm.setCursor(0, 2);
+ CodeMirror.commands.goLineDown(cm);
+ eqCharPos(cm.getCursor(), Pos(1, 4));
+ cm.setCursor(0, 2);
+ cm.replaceSelection("hi");
+ eqCharPos(w.find(), Pos(0, 2));
+ cm.setCursor(0, 1);
+ cm.replaceSelection("ay");
+ eqCharPos(w.find(), Pos(0, 4));
+ eq(cm.getLine(0), "uayuhiuu");
+}, {value: "uuuu\nuuuuuu"});
+
+testCM("wrappingAndResizing", function(cm) {
+ cm.setSize(null, "auto");
+ cm.setOption("lineWrapping", true);
+ var wrap = cm.getWrapperElement(), h0 = wrap.offsetHeight;
+ var doc = "xxx xxx xxx xxx xxx";
+ cm.setValue(doc);
+ for (var step = 10, w = cm.charCoords(Pos(0, 18), "div").right;; w += step) {
+ cm.setSize(w);
+ if (wrap.offsetHeight <= h0 * (opera_lt10 ? 1.2 : 1.5)) {
+ if (step == 10) { w -= 10; step = 1; }
+ else break;
+ }
+ }
+ // Ensure that putting the cursor at the end of the maximally long
+ // line doesn't cause wrapping to happen.
+ cm.setCursor(Pos(0, doc.length));
+ eq(wrap.offsetHeight, h0);
+ cm.replaceSelection("x");
+ is(wrap.offsetHeight > h0, "wrapping happens");
+ // Now add a max-height and, in a document consisting of
+ // almost-wrapped lines, go over it so that a scrollbar appears.
+ cm.setValue(doc + "\n" + doc + "\n");
+ cm.getScrollerElement().style.maxHeight = "100px";
+ cm.replaceRange("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n!\n", Pos(2, 0));
+ forEach([Pos(0, doc.length), Pos(0, doc.length - 1),
+ Pos(0, 0), Pos(1, doc.length), Pos(1, doc.length - 1)],
+ function(pos) {
+ var coords = cm.charCoords(pos);
+ eqCharPos(pos, cm.coordsChar({left: coords.left + 2, top: coords.top + 5}));
+ });
+}, null, ie_lt8);
+
+testCM("measureEndOfLine", function(cm) {
+ if (phantom) return;
+ cm.setSize(null, "auto");
+ var inner = byClassName(cm.getWrapperElement(), "CodeMirror-lines")[0].firstChild;
+ var lh = inner.offsetHeight;
+ for (var step = 10, w = cm.charCoords(Pos(0, 7), "div").right;; w += step) {
+ cm.setSize(w);
+ if (inner.offsetHeight < 2.5 * lh) {
+ if (step == 10) { w -= 10; step = 1; }
+ else break;
+ }
+ }
+ cm.setValue(cm.getValue() + "\n\n");
+ var endPos = cm.charCoords(Pos(0, 18), "local");
+ is(endPos.top > lh * .8, "not at top");
+ is(endPos.left > w - 20, "at right");
+ endPos = cm.charCoords(Pos(0, 18));
+ eqCursorPos(cm.coordsChar({left: endPos.left, top: endPos.top + 5}), Pos(0, 18, "before"));
+
+ var wrapPos = cm.cursorCoords(Pos(0, 9, "before"));
+ is(wrapPos.top < endPos.top, "wrapPos is actually in first line");
+ eqCursorPos(cm.coordsChar({left: wrapPos.left + 10, top: wrapPos.top}), Pos(0, 9, "before"));
+}, {mode: "text/html", value: "<!-- foo barrr -->", lineWrapping: true}, ie_lt8 || opera_lt10);
+
+testCM("measureWrappedEndOfLine", function(cm) {
+ if (phantom) return;
+ cm.setSize(null, "auto");
+ var inner = byClassName(cm.getWrapperElement(), "CodeMirror-lines")[0].firstChild;
+ var lh = inner.offsetHeight;
+ for (var step = 10, w = cm.charCoords(Pos(0, 7), "div").right;; w += step) {
+ cm.setSize(w);
+ if (inner.offsetHeight < 2.5 * lh) {
+ if (step == 10) { w -= 10; step = 1; }
+ else break;
+ }
+ }
+ for (var i = 0; i < 3; ++i) {
+ var endPos = cm.charCoords(Pos(0, 12)); // Next-to-last since last would wrap (#1862)
+ endPos.left += w; // Add width of editor just to be sure that we are behind last character
+ eqCursorPos(cm.coordsChar(endPos), Pos(0, 13, "before"));
+ endPos.left += w * 100;
+ eqCursorPos(cm.coordsChar(endPos), Pos(0, 13, "before"));
+ cm.setValue("0123456789abcابجابجابجابج");
+ if (i == 1) {
+ var node = document.createElement("div");
+ node.innerHTML = "hi"; node.style.height = "30px";
+ cm.addLineWidget(0, node, {above: true});
+ }
+ }
+}, {mode: "text/html", value: "0123456789abcde0123456789", lineWrapping: true}, ie_lt8 || opera_lt10);
+
+testCM("measureEndOfLineBidi", function(cm) {
+ eqCursorPos(cm.coordsChar({left: 5000, top: cm.charCoords(Pos(0, 0)).top}), Pos(0, 8, "after"))
+}, {value: "إإإإuuuuإإإإ"})
+
+testCM("measureWrappedBidiLevel2", function(cm) {
+ cm.setSize(cm.charCoords(Pos(0, 6), "editor").right + 60)
+ var c9 = cm.charCoords(Pos(0, 9))
+ eqCharPos(cm.coordsChar({left: c9.right - 1, top: c9.top + 1}), Pos(0, 9))
+}, {value: "foobar إإ إإ إإ إإ 555 بببببب", lineWrapping: true})
+
+testCM("measureWrappedBeginOfLine", function(cm) {
+ if (phantom) return;
+ cm.setSize(null, "auto");
+ var inner = byClassName(cm.getWrapperElement(), "CodeMirror-lines")[0].firstChild;
+ var lh = inner.offsetHeight;
+ for (var step = 10, w = cm.charCoords(Pos(0, 7), "div").right;; w += step) {
+ cm.setSize(w);
+ if (inner.offsetHeight < 2.5 * lh) {
+ if (step == 10) { w -= 10; step = 1; }
+ else break;
+ }
+ }
+ var beginOfSecondLine = Pos(0, 13, "after");
+ for (var i = 0; i < 2; ++i) {
+ var beginPos = cm.charCoords(Pos(0, 0));
+ beginPos.left -= w;
+ eqCursorPos(cm.coordsChar(beginPos), Pos(0, 0, "after"));
+ beginPos = cm.cursorCoords(beginOfSecondLine);
+ beginPos.left = 0;
+ eqCursorPos(cm.coordsChar(beginPos), beginOfSecondLine);
+ cm.setValue("0123456789abcابجابجابجابج");
+ beginOfSecondLine = Pos(0, 25, "before");
+ }
+}, {mode: "text/html", value: "0123456789abcde0123456789", lineWrapping: true});
+
+testCM("scrollVerticallyAndHorizontally", function(cm) {
+ if (cm.getOption("inputStyle") != "textarea") return;
+ cm.setSize(100, 100);
+ addDoc(cm, 40, 40);
+ cm.setCursor(39);
+ var wrap = cm.getWrapperElement(), bar = byClassName(wrap, "CodeMirror-vscrollbar")[0];
+ is(bar.offsetHeight < wrap.offsetHeight, "vertical scrollbar limited by horizontal one");
+ var cursorBox = byClassName(wrap, "CodeMirror-cursor")[0].getBoundingClientRect();
+ var editorBox = wrap.getBoundingClientRect();
+ is(cursorBox.bottom < editorBox.top + cm.getScrollerElement().clientHeight,
+ "bottom line visible");
+}, {lineNumbers: true});
+
+testCM("moveVstuck", function(cm) {
+ var lines = byClassName(cm.getWrapperElement(), "CodeMirror-lines")[0].firstChild, h0 = lines.offsetHeight;
+ var val = "fooooooooooooooooooooooooo baaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaar\n";
+ cm.setValue(val);
+ for (var w = cm.charCoords(Pos(0, 26), "div").right * 2.8;; w += 5) {
+ cm.setSize(w);
+ if (lines.offsetHeight <= 3.5 * h0) break;
+ }
+ cm.setCursor(Pos(0, val.length - 1));
+ cm.moveV(-1, "line");
+ eqCursorPos(cm.getCursor(), Pos(0, 27, "before"));
+ is(cm.cursorCoords(null, "local").top < h0, "cursor is in first visual line");
+}, {lineWrapping: true}, ie_lt8 || opera_lt10);
+
+testCM("collapseOnMove", function(cm) {
+ cm.setSelection(Pos(0, 1), Pos(2, 4));
+ cm.execCommand("goLineUp");
+ is(!cm.somethingSelected());
+ eqCharPos(cm.getCursor(), Pos(0, 1));
+ cm.setSelection(Pos(0, 1), Pos(2, 4));
+ cm.execCommand("goPageDown");
+ is(!cm.somethingSelected());
+ eqCharPos(cm.getCursor(), Pos(2, 4));
+ cm.execCommand("goLineUp");
+ cm.execCommand("goLineUp");
+ eqCharPos(cm.getCursor(), Pos(0, 4));
+ cm.setSelection(Pos(0, 1), Pos(2, 4));
+ cm.execCommand("goCharLeft");
+ is(!cm.somethingSelected());
+ eqCharPos(cm.getCursor(), Pos(0, 1));
+}, {value: "aaaaa\nb\nccccc"});
+
+testCM("clickTab", function(cm) {
+ var p0 = cm.charCoords(Pos(0, 0));
+ eqCharPos(cm.coordsChar({left: p0.left + 5, top: p0.top + 5}), Pos(0, 0));
+ eqCharPos(cm.coordsChar({left: p0.right - 5, top: p0.top + 5}), Pos(0, 1));
+}, {value: "\t\n\n", lineWrapping: true, tabSize: 8});
+
+testCM("verticalScroll", function(cm) {
+ cm.setSize(100, 200);
+ cm.setValue("foo\nbar\nbaz\n");
+ var sc = cm.getScrollerElement(), baseWidth = sc.scrollWidth;
+ cm.replaceRange("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah", Pos(0, 0), Pos(0));
+ is(sc.scrollWidth > baseWidth, "scrollbar present");
+ cm.replaceRange("foo", Pos(0, 0), Pos(0));
+ if (!phantom) eq(sc.scrollWidth, baseWidth, "scrollbar gone");
+ cm.replaceRange("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah", Pos(0, 0), Pos(0));
+ cm.replaceRange("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbh", Pos(1, 0), Pos(1));
+ is(sc.scrollWidth > baseWidth, "present again");
+ var curWidth = sc.scrollWidth;
+ cm.replaceRange("foo", Pos(0, 0), Pos(0));
+ is(sc.scrollWidth < curWidth, "scrollbar smaller");
+ is(sc.scrollWidth > baseWidth, "but still present");
+});
+
+testCM("extraKeys", function(cm) {
+ var outcome;
+ function fakeKey(expected, code, props) {
+ if (typeof code == "string") code = code.charCodeAt(0);
+ var e = {type: "keydown", keyCode: code, preventDefault: function(){}, stopPropagation: function(){}};
+ if (props) for (var n in props) e[n] = props[n];
+ outcome = null;
+ cm.triggerOnKeyDown(e);
+ eq(outcome, expected);
+ }
+ CodeMirror.commands.testCommand = function() {outcome = "tc";};
+ CodeMirror.commands.goTestCommand = function() {outcome = "gtc";};
+ cm.setOption("extraKeys", {"Shift-X": function() {outcome = "sx";},
+ "X": function() {outcome = "x";},
+ "Ctrl-Alt-U": function() {outcome = "cau";},
+ "End": "testCommand",
+ "Home": "goTestCommand",
+ "Tab": false});
+ fakeKey(null, "U");
+ fakeKey("cau", "U", {ctrlKey: true, altKey: true});
+ fakeKey(null, "U", {shiftKey: true, ctrlKey: true, altKey: true});
+ fakeKey("x", "X");
+ fakeKey("sx", "X", {shiftKey: true});
+ fakeKey("tc", 35);
+ fakeKey(null, 35, {shiftKey: true});
+ fakeKey("gtc", 36);
+ fakeKey("gtc", 36, {shiftKey: true});
+ fakeKey(null, 9);
+}, null, window.opera && mac);
+
+testCM("wordMovementCommands", function(cm) {
+ cm.execCommand("goWordLeft");
+ eqCursorPos(cm.getCursor(), Pos(0, 0));
+ cm.execCommand("goWordRight"); cm.execCommand("goWordRight");
+ eqCursorPos(cm.getCursor(), Pos(0, 7, "before"));
+ cm.execCommand("goWordLeft");
+ eqCursorPos(cm.getCursor(), Pos(0, 5, "after"));
+ cm.execCommand("goWordRight"); cm.execCommand("goWordRight");
+ eqCursorPos(cm.getCursor(), Pos(0, 12, "before"));
+ cm.execCommand("goWordLeft");
+ eqCursorPos(cm.getCursor(), Pos(0, 9, "after"));
+ cm.execCommand("goWordRight"); cm.execCommand("goWordRight"); cm.execCommand("goWordRight");
+ eqCursorPos(cm.getCursor(), Pos(0, 24, "before"));
+ cm.execCommand("goWordRight"); cm.execCommand("goWordRight");
+ eqCursorPos(cm.getCursor(), Pos(1, 9, "before"));
+ cm.execCommand("goWordRight");
+ eqCursorPos(cm.getCursor(), Pos(1, 13, "before"));
+ cm.execCommand("goWordRight"); cm.execCommand("goWordRight");
+ eqCharPos(cm.getCursor(), Pos(2, 0));
+}, {value: "this is (the) firstline.\na foo12\u00e9\u00f8\u00d7bar\n"});
+
+testCM("groupMovementCommands", function(cm) {
+ cm.execCommand("goGroupLeft");
+ eqCursorPos(cm.getCursor(), Pos(0, 0));
+ cm.execCommand("goGroupRight");
+ eqCursorPos(cm.getCursor(), Pos(0, 4, "before"));
+ cm.execCommand("goGroupRight");
+ eqCursorPos(cm.getCursor(), Pos(0, 7, "before"));
+ cm.execCommand("goGroupRight");
+ eqCursorPos(cm.getCursor(), Pos(0, 10, "before"));
+ cm.execCommand("goGroupLeft");
+ eqCursorPos(cm.getCursor(), Pos(0, 7, "after"));
+ cm.execCommand("goGroupRight"); cm.execCommand("goGroupRight"); cm.execCommand("goGroupRight");
+ eqCursorPos(cm.getCursor(), Pos(0, 15, "before"));
+ cm.setCursor(Pos(0, 17));
+ cm.execCommand("goGroupLeft");
+ eqCursorPos(cm.getCursor(), Pos(0, 16, "after"));
+ cm.execCommand("goGroupLeft");
+ eqCursorPos(cm.getCursor(), Pos(0, 14, "after"));
+ cm.execCommand("goGroupRight"); cm.execCommand("goGroupRight");
+ eqCursorPos(cm.getCursor(), Pos(0, 20, "before"));
+ cm.execCommand("goGroupRight");
+ eqCursorPos(cm.getCursor(), Pos(1, 0, "after"));
+ cm.execCommand("goGroupRight");
+ eqCursorPos(cm.getCursor(), Pos(1, 2, "before"));
+ cm.execCommand("goGroupRight");
+ eqCursorPos(cm.getCursor(), Pos(1, 5, "before"));
+ cm.execCommand("goGroupLeft"); cm.execCommand("goGroupLeft");
+ eqCursorPos(cm.getCursor(), Pos(1, 0, "after"));
+ cm.execCommand("goGroupLeft");
+ eqCursorPos(cm.getCursor(), Pos(0, 20, "after"));
+ cm.execCommand("goGroupLeft");
+ eqCursorPos(cm.getCursor(), Pos(0, 16, "after"));
+}, {value: "booo ba---quux. ffff\n abc d"});
+
+testCM("groupsAndWhitespace", function(cm) {
+ var positions = [Pos(0, 0), Pos(0, 2), Pos(0, 5), Pos(0, 9), Pos(0, 11),
+ Pos(1, 0), Pos(1, 2), Pos(1, 5)];
+ for (var i = 1; i < positions.length; i++) {
+ cm.execCommand("goGroupRight");
+ eqCharPos(cm.getCursor(), positions[i]);
+ }
+ for (var i = positions.length - 2; i >= 0; i--) {
+ cm.execCommand("goGroupLeft");
+ eqCharPos(cm.getCursor(), i == 2 ? Pos(0, 6, "before") : positions[i]);
+ }
+}, {value: " foo +++ \n bar"});
+
+testCM("charMovementCommands", function(cm) {
+ cm.execCommand("goCharLeft"); cm.execCommand("goColumnLeft");
+ eqCursorPos(cm.getCursor(), Pos(0, 0));
+ cm.execCommand("goCharRight"); cm.execCommand("goCharRight");
+ eqCursorPos(cm.getCursor(), Pos(0, 2, "before"));
+ cm.setCursor(Pos(1, 0));
+ cm.execCommand("goColumnLeft");
+ eqCursorPos(cm.getCursor(), Pos(1, 0));
+ cm.execCommand("goCharLeft");
+ eqCursorPos(cm.getCursor(), Pos(0, 5, "before"));
+ cm.execCommand("goColumnRight");
+ eqCursorPos(cm.getCursor(), Pos(0, 5, "before"));
+ cm.execCommand("goCharRight");
+ eqCursorPos(cm.getCursor(), Pos(1, 0, "after"));
+ cm.execCommand("goLineEnd");
+ eqCursorPos(cm.getCursor(), Pos(1, 5, "before"));
+ cm.execCommand("goLineStartSmart");
+ eqCursorPos(cm.getCursor(), Pos(1, 1, "after"));
+ cm.execCommand("goLineStartSmart");
+ eqCursorPos(cm.getCursor(), Pos(1, 0, "after"));
+ cm.setCursor(Pos(2, 0));
+ cm.execCommand("goCharRight"); cm.execCommand("goColumnRight");
+ eqCursorPos(cm.getCursor(), Pos(2, 0));
+}, {value: "line1\n ine2\n"});
+
+testCM("verticalMovementCommands", function(cm) {
+ cm.execCommand("goLineUp");
+ eqCharPos(cm.getCursor(), Pos(0, 0));
+ cm.execCommand("goLineDown");
+ if (!phantom) // This fails in PhantomJS, though not in a real Webkit
+ eqCharPos(cm.getCursor(), Pos(1, 0));
+ cm.setCursor(Pos(1, 12));
+ cm.execCommand("goLineDown");
+ eqCharPos(cm.getCursor(), Pos(2, 5));
+ cm.execCommand("goLineDown");
+ eqCharPos(cm.getCursor(), Pos(3, 0));
+ cm.execCommand("goLineUp");
+ eqCharPos(cm.getCursor(), Pos(2, 5));
+ cm.execCommand("goLineUp");
+ eqCharPos(cm.getCursor(), Pos(1, 12));
+ cm.execCommand("goPageDown");
+ eqCharPos(cm.getCursor(), Pos(5, 0));
+ cm.execCommand("goPageDown"); cm.execCommand("goLineDown");
+ eqCharPos(cm.getCursor(), Pos(5, 0));
+ cm.execCommand("goPageUp");
+ eqCharPos(cm.getCursor(), Pos(0, 0));
+}, {value: "line1\nlong long line2\nline3\n\nline5\n"});
+
+testCM("verticalMovementCommandsWrapping", function(cm) {
+ cm.setSize(120);
+ cm.setCursor(Pos(0, 5));
+ cm.execCommand("goLineDown");
+ eq(cm.getCursor().line, 0);
+ is(cm.getCursor().ch > 5, "moved beyond wrap");
+ for (var i = 0; ; ++i) {
+ is(i < 20, "no endless loop");
+ cm.execCommand("goLineDown");
+ var cur = cm.getCursor();
+ if (cur.line == 1) eq(cur.ch, 5);
+ if (cur.line == 2) { eq(cur.ch, 1); break; }
+ }
+}, {value: "a very long line that wraps around somehow so that we can test cursor movement\nshortone\nk",
+ lineWrapping: true});
+
+testCM("verticalMovementCommandsSingleLine", function(cm) {
+ cm.display.wrapper.style.height = "auto";
+ cm.refresh();
+ cm.execCommand("goLineUp");
+ eqCursorPos(cm.getCursor(), Pos(0, 0));
+ cm.execCommand("goLineDown");
+ eqCursorPos(cm.getCursor(), Pos(0, 11));
+ cm.setCursor(Pos(0, 5));
+ cm.execCommand("goLineDown");
+ eqCursorPos(cm.getCursor(), Pos(0, 11));
+ cm.execCommand("goLineDown");
+ eqCursorPos(cm.getCursor(), Pos(0, 11));
+ cm.execCommand("goLineUp");
+ eqCursorPos(cm.getCursor(), Pos(0, 0));
+ cm.execCommand("goLineUp");
+ eqCursorPos(cm.getCursor(), Pos(0, 0));
+ cm.execCommand("goPageDown");
+ eqCursorPos(cm.getCursor(), Pos(0, 11));
+ cm.execCommand("goPageDown"); cm.execCommand("goLineDown");
+ eqCursorPos(cm.getCursor(), Pos(0, 11));
+ cm.execCommand("goPageUp");
+ eqCursorPos(cm.getCursor(), Pos(0, 0));
+ cm.setCursor(Pos(0, 5));
+ cm.execCommand("goPageUp");
+ eqCursorPos(cm.getCursor(), Pos(0, 0));
+ cm.setCursor(Pos(0, 5));
+ cm.execCommand("goPageDown");
+ eqCursorPos(cm.getCursor(), Pos(0, 11));
+}, {value: "single line"});
+
+
+testCM("rtlMovement", function(cm) {
+ if (cm.getOption("inputStyle") != "textarea") return;
+ forEach(["خحج", "خحabcخحج", "abخحخحجcd", "abخde", "abخح2342خ1حج", "خ1ح2خح3حxج",
+ "خحcd", "1خحcd", "abcdeح1ج", "خمرحبها مها!", "foobarر", "خ ة ق",
+ "<img src=\"/בדיקה3.jpg\">", "يتم السحب في 05 فبراير 2014"], function(line) {
+ cm.setValue(line + "\n"); cm.execCommand("goLineStart");
+ var cursors = byClassName(cm.getWrapperElement(), "CodeMirror-cursors")[0];
+ var cursor = cursors.firstChild;
+ var prevX = cursor.offsetLeft, prevY = cursor.offsetTop;
+ for (var i = 0; i <= line.length; ++i) {
+ cm.execCommand("goCharRight");
+ cursor = cursors.firstChild;
+ if (i == line.length) is(cursor.offsetTop > prevY, "next line");
+ else is(cursor.offsetLeft > prevX, "moved right");
+ prevX = cursor.offsetLeft; prevY = cursor.offsetTop;
+ }
+ cm.setCursor(0, 0); cm.execCommand("goLineEnd");
+ prevX = cursors.firstChild.offsetLeft;
+ for (var i = 0; i < line.length; ++i) {
+ cm.execCommand("goCharLeft");
+ cursor = cursors.firstChild;
+ is(cursor.offsetLeft < prevX, "moved left");
+ prevX = cursor.offsetLeft;
+ }
+ });
+}, null, ie_lt9);
+
+// Verify that updating a line clears its bidi ordering
+testCM("bidiUpdate", function(cm) {
+ cm.setCursor(Pos(0, 2, "before"));
+ cm.replaceSelection("خحج", "start");
+ cm.execCommand("goCharRight");
+ eqCursorPos(cm.getCursor(), Pos(0, 6, "before"));
+}, {value: "abcd\n"});
+
+testCM("movebyTextUnit", function(cm) {
+ cm.setValue("בְּרֵאשִ\nééé́\n");
+ cm.execCommand("goLineStart");
+ for (var i = 0; i < 4; ++i) cm.execCommand("goCharRight");
+ eqCursorPos(cm.getCursor(), Pos(0, 0, "after"));
+ cm.execCommand("goCharRight");
+ eqCursorPos(cm.getCursor(), Pos(1, 0, "after"));
+ cm.execCommand("goCharRight");
+ cm.execCommand("goCharRight");
+ eqCursorPos(cm.getCursor(), Pos(1, 4, "before"));
+ cm.execCommand("goCharRight");
+ eqCursorPos(cm.getCursor(), Pos(1, 7, "before"));
+});
+
+testCM("lineChangeEvents", function(cm) {
+ addDoc(cm, 3, 5);
+ var log = [], want = ["ch 0", "ch 1", "del 2", "ch 0", "ch 0", "del 1", "del 3", "del 4"];
+ for (var i = 0; i < 5; ++i) {
+ CodeMirror.on(cm.getLineHandle(i), "delete", function(i) {
+ return function() {log.push("del " + i);};
+ }(i));
+ CodeMirror.on(cm.getLineHandle(i), "change", function(i) {
+ return function() {log.push("ch " + i);};
+ }(i));
+ }
+ cm.replaceRange("x", Pos(0, 1));
+ cm.replaceRange("xy", Pos(1, 1), Pos(2));
+ cm.replaceRange("foo\nbar", Pos(0, 1));
+ cm.replaceRange("", Pos(0, 0), Pos(cm.lineCount()));
+ eq(log.length, want.length, "same length");
+ for (var i = 0; i < log.length; ++i)
+ eq(log[i], want[i]);
+});
+
+testCM("scrollEntirelyToRight", function(cm) {
+ if (phantom || cm.getOption("inputStyle") != "textarea") return;
+ addDoc(cm, 500, 2);
+ cm.setCursor(Pos(0, 500));
+ var wrap = cm.getWrapperElement(), cur = byClassName(wrap, "CodeMirror-cursor")[0];
+ is(wrap.getBoundingClientRect().right > cur.getBoundingClientRect().left);
+});
+
+testCM("lineWidgets", function(cm) {
+ addDoc(cm, 500, 3);
+ var last = cm.charCoords(Pos(2, 0));
+ var node = document.createElement("div");
+ node.innerHTML = "hi";
+ var widget = cm.addLineWidget(1, node);
+ is(last.top < cm.charCoords(Pos(2, 0)).top, "took up space");
+ cm.setCursor(Pos(1, 1));
+ cm.execCommand("goLineDown");
+ eqCharPos(cm.getCursor(), Pos(2, 1));
+ cm.execCommand("goLineUp");
+ eqCharPos(cm.getCursor(), Pos(1, 1));
+});
+
+testCM("lineWidgetFocus", function(cm) {
+ var place = document.getElementById("testground");
+ place.className = "offscreen";
+ try {
+ addDoc(cm, 500, 10);
+ var node = document.createElement("input");
+ var widget = cm.addLineWidget(1, node);
+ node.focus();
+ eq(document.activeElement, node);
+ cm.replaceRange("new stuff", Pos(1, 0));
+ eq(document.activeElement, node);
+ } finally {
+ place.className = "";
+ }
+});
+
+testCM("lineWidgetCautiousRedraw", function(cm) {
+ var node = document.createElement("div");
+ node.innerHTML = "hahah";
+ var w = cm.addLineWidget(0, node);
+ var redrawn = false;
+ w.on("redraw", function() { redrawn = true; });
+ cm.replaceSelection("0");
+ is(!redrawn);
+}, {value: "123\n456"});
+
+
+var knownScrollbarWidth;
+function scrollbarWidth(measure) {
+ if (knownScrollbarWidth != null) return knownScrollbarWidth;
+ var div = document.createElement('div');
+ div.style.cssText = "width: 50px; height: 50px; overflow-x: scroll";
+ document.body.appendChild(div);
+ knownScrollbarWidth = div.offsetHeight - div.clientHeight;
+ document.body.removeChild(div);
+ return knownScrollbarWidth || 0;
+}
+
+testCM("lineWidgetChanged", function(cm) {
+ addDoc(cm, 2, 300);
+ var halfScrollbarWidth = scrollbarWidth(cm.display.measure)/2;
+ cm.setOption('lineNumbers', true);
+ cm.setSize(600, cm.defaultTextHeight() * 50);
+ cm.scrollTo(null, cm.heightAtLine(125, "local"));
+
+ var expectedWidgetHeight = 60;
+ var expectedLinesInWidget = 3;
+ function w() {
+ var node = document.createElement("div");
+ // we use these children with just under half width of the line to check measurements are made with correct width
+ // when placed in the measure div.
+ // If the widget is measured at a width much narrower than it is displayed at, the underHalf children will span two lines and break the test.
+ // If the widget is measured at a width much wider than it is displayed at, the overHalf children will combine and break the test.
+ // Note that this test only checks widgets where coverGutter is true, because these require extra styling to get the width right.
+ // It may also be worthwhile to check this for non-coverGutter widgets.
+ // Visually:
+ // Good:
+ // | ------------- display width ------------- |
+ // | ------- widget-width when measured ------ |
+ // | | -- under-half -- | | -- under-half -- | |
+ // | | --- over-half --- | |
+ // | | --- over-half --- | |
+ // Height: measured as 3 lines, same as it will be when actually displayed
+
+ // Bad (too narrow):
+ // | ------------- display width ------------- |
+ // | ------ widget-width when measured ----- | < -- uh oh
+ // | | -- under-half -- | |
+ // | | -- under-half -- | | < -- when measured, shoved to next line
+ // | | --- over-half --- | |
+ // | | --- over-half --- | |
+ // Height: measured as 4 lines, more than expected . Will be displayed as 3 lines!
+
+ // Bad (too wide):
+ // | ------------- display width ------------- |
+ // | -------- widget-width when measured ------- | < -- uh oh
+ // | | -- under-half -- | | -- under-half -- | |
+ // | | --- over-half --- | | --- over-half --- | | < -- when measured, combined on one line
+ // Height: measured as 2 lines, less than expected. Will be displayed as 3 lines!
+
+ var barelyUnderHalfWidthHtml = '<div style="display: inline-block; height: 1px; width: '+(285 - halfScrollbarWidth)+'px;"></div>';
+ var barelyOverHalfWidthHtml = '<div style="display: inline-block; height: 1px; width: '+(305 - halfScrollbarWidth)+'px;"></div>';
+ node.innerHTML = new Array(3).join(barelyUnderHalfWidthHtml) + new Array(3).join(barelyOverHalfWidthHtml);
+ node.style.cssText = "background: yellow;font-size:0;line-height: " + (expectedWidgetHeight/expectedLinesInWidget) + "px;";
+ return node;
+ }
+ var info0 = cm.getScrollInfo();
+ var w0 = cm.addLineWidget(0, w(), { coverGutter: true });
+ var w150 = cm.addLineWidget(150, w(), { coverGutter: true });
+ var w300 = cm.addLineWidget(300, w(), { coverGutter: true });
+ var info1 = cm.getScrollInfo();
+ eq(info0.height + (3 * expectedWidgetHeight), info1.height);
+ eq(info0.top + expectedWidgetHeight, info1.top);
+ expectedWidgetHeight = 12;
+ w0.node.style.lineHeight = w150.node.style.lineHeight = w300.node.style.lineHeight = (expectedWidgetHeight/expectedLinesInWidget) + "px";
+ w0.changed(); w150.changed(); w300.changed();
+ var info2 = cm.getScrollInfo();
+ eq(info0.height + (3 * expectedWidgetHeight), info2.height);
+ eq(info0.top + expectedWidgetHeight, info2.top);
+});
+
+testCM("lineWidgetIssue5486", function(cm) {
+ // [prepare]
+ // 2nd line is combined to 1st line due to markText
+ // 2nd line has a lineWidget below
+
+ cm.setValue("Lorem\nIpsue\nDollar")
+
+ var el = document.createElement('div')
+ el.style.height='50px'
+ el.textContent = '[[LINE WIDGET]]'
+
+ var lineWidget = cm.addLineWidget(1, el, {
+ above: false,
+ coverGutter: false,
+ noHScroll: false,
+ showIfHidden: false,
+ })
+
+ var marker = document.createElement('span')
+ marker.textContent = '[--]'
+
+ cm.markText({line:0, ch: 1}, {line:1, ch: 4}, {
+ replacedWith: marker
+ })
+
+ // before resizing the lineWidget, measure 3rd line position
+
+ var measure_1 = Math.round(cm.charCoords({line:2, ch:0}).top)
+
+ // resize lineWidget, height + 50 px
+
+ el.style.height='100px'
+ el.textContent += "\nlineWidget size changed.\nTry moving cursor to line 3?"
+
+ lineWidget.changed()
+
+ // re-measure 3rd line position
+ var measure_2 = Math.round(cm.charCoords({line:2, ch:0}).top)
+ eq(measure_2, measure_1 + 50)
+
+ // (extra test)
+ //
+ // add char to the right of the folded marker
+ // and re-measure 3rd line position
+
+ cm.replaceRange('-', {line:1, ch: 5})
+ var measure_3 = Math.round(cm.charCoords({line:2, ch:0}).top)
+ eq(measure_3, measure_2)
+});
+
+testCM("getLineNumber", function(cm) {
+ addDoc(cm, 2, 20);
+ var h1 = cm.getLineHandle(1);
+ eq(cm.getLineNumber(h1), 1);
+ cm.replaceRange("hi\nbye\n", Pos(0, 0));
+ eq(cm.getLineNumber(h1), 3);
+ cm.setValue("");
+ eq(cm.getLineNumber(h1), null);
+});
+
+testCM("jumpTheGap", function(cm) {
+ if (phantom) return;
+ var longLine = "abcdef ghiklmnop qrstuvw xyz ";
+ longLine += longLine; longLine += longLine; longLine += longLine;
+ cm.replaceRange(longLine, Pos(2, 0), Pos(2));
+ cm.setSize("200px", null);
+ cm.getWrapperElement().style.lineHeight = 2;
+ cm.refresh();
+ cm.setCursor(Pos(0, 1));
+ cm.execCommand("goLineDown");
+ eqCharPos(cm.getCursor(), Pos(1, 1));
+ cm.execCommand("goLineDown");
+ eqCharPos(cm.getCursor(), Pos(2, 1));
+ cm.execCommand("goLineDown");
+ eq(cm.getCursor().line, 2);
+ is(cm.getCursor().ch > 1);
+ cm.execCommand("goLineUp");
+ eqCharPos(cm.getCursor(), Pos(2, 1));
+ cm.execCommand("goLineUp");
+ eqCharPos(cm.getCursor(), Pos(1, 1));
+ var node = document.createElement("div");
+ node.innerHTML = "hi"; node.style.height = "30px";
+ cm.addLineWidget(0, node);
+ cm.addLineWidget(1, node.cloneNode(true), {above: true});
+ cm.setCursor(Pos(0, 2));
+ cm.execCommand("goLineDown");
+ eqCharPos(cm.getCursor(), Pos(1, 2));
+ cm.execCommand("goLineUp");
+ eqCharPos(cm.getCursor(), Pos(0, 2));
+}, {lineWrapping: true, value: "abc\ndef\nghi\njkl\n"});
+
+testCM("addLineClass", function(cm) {
+ function cls(line, text, bg, wrap, gutter) {
+ var i = cm.lineInfo(line);
+ eq(i.textClass, text);
+ eq(i.bgClass, bg);
+ eq(i.wrapClass, wrap);
+ if (typeof i.handle.gutterClass !== 'undefined') {
+ eq(i.handle.gutterClass, gutter);
+ }
+ }
+ cm.addLineClass(0, "text", "foo");
+ cm.addLineClass(0, "text", "bar");
+ cm.addLineClass(1, "background", "baz");
+ cm.addLineClass(1, "wrap", "foo");
+ cm.addLineClass(1, "gutter", "gutter-class");
+ cls(0, "foo bar", null, null, null);
+ cls(1, null, "baz", "foo", "gutter-class");
+ var lines = cm.display.lineDiv;
+ eq(byClassName(lines, "foo").length, 2);
+ eq(byClassName(lines, "bar").length, 1);
+ eq(byClassName(lines, "baz").length, 1);
+ eq(byClassName(lines, "gutter-class").length, 2); // Gutter classes are reflected in 2 nodes
+ cm.removeLineClass(0, "text", "foo");
+ cls(0, "bar", null, null, null);
+ cm.removeLineClass(0, "text", "foo");
+ cls(0, "bar", null, null, null);
+ cm.removeLineClass(0, "text", "bar");
+ cls(0, null, null, null);
+
+ cm.addLineClass(1, "wrap", "quux");
+ cls(1, null, "baz", "foo quux", "gutter-class");
+ cm.removeLineClass(1, "wrap");
+ cls(1, null, "baz", null, "gutter-class");
+ cm.removeLineClass(1, "gutter", "gutter-class");
+ eq(byClassName(lines, "gutter-class").length, 0);
+ cls(1, null, "baz", null, null);
+
+ cm.addLineClass(1, "gutter", "gutter-class");
+ cls(1, null, "baz", null, "gutter-class");
+ cm.removeLineClass(1, "gutter", "gutter-class");
+ cls(1, null, "baz", null, null);
+
+}, {value: "hohoho\n", lineNumbers: true});
+
+testCM("atomicMarker", function(cm) {
+ addDoc(cm, 10, 10);
+
+ function atom(ll, cl, lr, cr, li, ri, ls, rs) {
+ var options = {
+ atomic: true,
+ inclusiveLeft: li,
+ inclusiveRight: ri
+ };
+
+ if (ls === true || ls === false) options["selectLeft"] = ls;
+ if (rs === true || rs === false) options["selectRight"] = rs;
+
+ return cm.markText(Pos(ll, cl), Pos(lr, cr), options);
+ }
+
+ // Can cursor to the left and right of a normal marker by jumping across it
+ var m = atom(0, 1, 0, 5);
+ cm.setCursor(Pos(0, 1));
+ cm.execCommand("goCharRight");
+ eqCursorPos(cm.getCursor(), Pos(0, 5));
+ cm.execCommand("goCharLeft");
+ eqCursorPos(cm.getCursor(), Pos(0, 1));
+ m.clear();
+
+ // Can't cursor to the left of a marker when inclusiveLeft=true
+ m = atom(0, 0, 0, 5, true);
+ eqCursorPos(cm.getCursor(), Pos(0, 5), "pushed out");
+ cm.execCommand("goCharLeft");
+ eqCursorPos(cm.getCursor(), Pos(0, 5));
+ m.clear();
+
+ // Can't cursor to the left of a marker when inclusiveLeft=false and selectLeft=false
+ m = atom(0, 0, 0, 5, false, false, false);
+ cm.setCursor(Pos(0, 5));
+ eqCursorPos(cm.getCursor(), Pos(0, 5), "pushed out");
+ cm.execCommand("goCharLeft");
+ eqCursorPos(cm.getCursor(), Pos(0, 5));
+ m.clear();
+
+ // Can cursor to the left of a marker when inclusiveLeft=false and selectLeft=True
+ m = atom(0, 0, 0, 5, false, false, true);
+ cm.setCursor(Pos(0, 5));
+ eqCursorPos(cm.getCursor(), Pos(0, 5), "pushed out");
+ cm.execCommand("goCharLeft");
+ eqCursorPos(cm.getCursor(), Pos(0, 0));
+ m.clear();
+
+ // Can't cursor to the right of a marker when inclusiveRight=true
+ m = atom(0, 0, 0, 5, false, true);
+ cm.setCursor(Pos(0, 0));
+ eqCursorPos(cm.getCursor(), Pos(0, 0));
+ cm.execCommand("goCharRight");
+ eqCursorPos(cm.getCursor(), Pos(0, 6));
+ m.clear();
+
+ // Can't cursor to the right of a marker when inclusiveRight=false and selectRight=false
+ m = atom(0, 0, 0, 5, false, false, true, false);
+ cm.setCursor(Pos(0, 0));
+ eqCursorPos(cm.getCursor(), Pos(0, 0));
+ cm.execCommand("goCharRight");
+ eqCursorPos(cm.getCursor(), Pos(0, 6));
+ m.clear();
+
+ // Can cursor to the right of a marker when inclusiveRight=false and selectRight=True
+ m = atom(0, 0, 0, 5, false, false, true, true);
+ cm.setCursor(Pos(0, 0));
+ eqCursorPos(cm.getCursor(), Pos(0, 0));
+ cm.execCommand("goCharRight");
+ eqCursorPos(cm.getCursor(), Pos(0, 5));
+ m.clear();
+
+ // Can't cursor to the right of a multiline marker when inclusiveRight=true
+ m = atom(8, 4, 9, 10, false, true);
+ cm.setCursor(Pos(9, 8));
+ eqCursorPos(cm.getCursor(), Pos(8, 4), "set");
+ cm.execCommand("goCharRight");
+ eqCursorPos(cm.getCursor(), Pos(8, 4), "char right");
+ cm.execCommand("goLineDown");
+ eqCursorPos(cm.getCursor(), Pos(8, 4), "line down");
+ cm.execCommand("goCharLeft");
+ eqCursorPos(cm.getCursor(), Pos(8, 3, "after"));
+ m.clear();
+
+ // Cursor jumps across a multiline atomic marker,
+ // and backspace deletes the entire marker
+ m = atom(1, 1, 3, 8);
+ cm.setCursor(Pos(0, 0));
+ cm.setCursor(Pos(2, 0));
+ eqCursorPos(cm.getCursor(), Pos(3, 8));
+ cm.execCommand("goCharLeft");
+ eqCursorPos(cm.getCursor(), Pos(1, 1));
+ cm.execCommand("goCharRight");
+ eqCursorPos(cm.getCursor(), Pos(3, 8));
+ cm.execCommand("goLineUp");
+ eqCursorPos(cm.getCursor(), Pos(1, 1));
+ cm.execCommand("goLineDown");
+ eqCursorPos(cm.getCursor(), Pos(3, 8));
+ cm.execCommand("delCharBefore");
+ eq(cm.getValue().length, 80, "del chunk");
+ m.clear();
+ addDoc(cm, 10, 10);
+
+ // Delete before an atomic marker deletes the entire marker
+ m = atom(3, 0, 5, 5);
+ cm.setCursor(Pos(3, 0));
+ cm.execCommand("delWordAfter");
+ eq(cm.getValue().length, 82, "del chunk");
+ m.clear();
+ addDoc(cm, 10, 10);
+});
+
+testCM("selectionBias", function(cm) {
+ cm.markText(Pos(0, 1), Pos(0, 3), {atomic: true});
+ cm.setCursor(Pos(0, 2));
+ eqCursorPos(cm.getCursor(), Pos(0, 1));
+ cm.setCursor(Pos(0, 2));
+ eqCursorPos(cm.getCursor(), Pos(0, 3));
+ cm.setCursor(Pos(0, 2));
+ eqCursorPos(cm.getCursor(), Pos(0, 1));
+ cm.setCursor(Pos(0, 2), null, {bias: -1});
+ eqCursorPos(cm.getCursor(), Pos(0, 1));
+ cm.setCursor(Pos(0, 4));
+ cm.setCursor(Pos(0, 2), null, {bias: 1});
+ eqCursorPos(cm.getCursor(), Pos(0, 3));
+}, {value: "12345"});
+
+testCM("selectionHomeEnd", function(cm) {
+ cm.markText(Pos(1, 0), Pos(1, 1), {atomic: true, inclusiveLeft: true});
+ cm.markText(Pos(1, 3), Pos(1, 4), {atomic: true, inclusiveRight: true});
+ cm.setCursor(Pos(1, 2));
+ cm.execCommand("goLineStart");
+ eqCursorPos(cm.getCursor(), Pos(1, 1));
+ cm.execCommand("goLineEnd");
+ eqCursorPos(cm.getCursor(), Pos(1, 3));
+}, {value: "ab\ncdef\ngh"});
+
+testCM("readOnlyMarker", function(cm) {
+ function mark(ll, cl, lr, cr, at) {
+ return cm.markText(Pos(ll, cl), Pos(lr, cr),
+ {readOnly: true, atomic: at});
+ }
+ var m = mark(0, 1, 0, 4);
+ cm.setCursor(Pos(0, 2));
+ cm.replaceSelection("hi", "end");
+ eqCursorPos(cm.getCursor(), Pos(0, 2));
+ eq(cm.getLine(0), "abcde");
+ cm.execCommand("selectAll");
+ cm.replaceSelection("oops", "around");
+ eq(cm.getValue(), "oopsbcd");
+ cm.undo();
+ eqCursorPos(m.find().from, Pos(0, 1));
+ eqCursorPos(m.find().to, Pos(0, 4));
+ m.clear();
+ cm.setCursor(Pos(0, 2));
+ cm.replaceSelection("hi", "around");
+ eq(cm.getLine(0), "abhicde");
+ eqCursorPos(cm.getCursor(), Pos(0, 4));
+ m = mark(0, 2, 2, 2, true);
+ cm.setSelection(Pos(1, 1), Pos(2, 4));
+ cm.replaceSelection("t", "end");
+ eqCursorPos(cm.getCursor(), Pos(2, 3));
+ eq(cm.getLine(2), "klto");
+ cm.execCommand("goCharLeft");
+ cm.execCommand("goCharLeft");
+ eqCursorPos(cm.getCursor(), Pos(0, 2));
+ cm.setSelection(Pos(0, 1), Pos(0, 3));
+ cm.replaceSelection("xx", "around");
+ eqCursorPos(cm.getCursor(), Pos(0, 3));
+ eq(cm.getLine(0), "axxhicde");
+}, {value: "abcde\nfghij\nklmno\n"});
+
+testCM("dirtyBit", function(cm) {
+ eq(cm.isClean(), true);
+ cm.replaceSelection("boo", null, "test");
+ eq(cm.isClean(), false);
+ cm.undo();
+ eq(cm.isClean(), true);
+ cm.replaceSelection("boo", null, "test");
+ cm.replaceSelection("baz", null, "test");
+ cm.undo();
+ eq(cm.isClean(), false);
+ cm.markClean();
+ eq(cm.isClean(), true);
+ cm.undo();
+ eq(cm.isClean(), false);
+ cm.redo();
+ eq(cm.isClean(), true);
+});
+
+testCM("changeGeneration", function(cm) {
+ cm.replaceSelection("x");
+ var softGen = cm.changeGeneration();
+ cm.replaceSelection("x");
+ cm.undo();
+ eq(cm.getValue(), "");
+ is(!cm.isClean(softGen));
+ cm.replaceSelection("x");
+ var hardGen = cm.changeGeneration(true);
+ cm.replaceSelection("x");
+ cm.undo();
+ eq(cm.getValue(), "x");
+ is(cm.isClean(hardGen));
+});
+
+testCM("addKeyMap", function(cm) {
+ function sendKey(code) {
+ cm.triggerOnKeyDown({type: "keydown", keyCode: code,
+ preventDefault: function(){}, stopPropagation: function(){}});
+ }
+
+ sendKey(39);
+ eqCursorPos(cm.getCursor(), Pos(0, 1, "before"));
+ var test = 0;
+ var map1 = {Right: function() { ++test; }}, map2 = {Right: function() { test += 10; }}
+ cm.addKeyMap(map1);
+ sendKey(39);
+ eqCursorPos(cm.getCursor(), Pos(0, 1, "before"));
+ eq(test, 1);
+ cm.addKeyMap(map2, true);
+ sendKey(39);
+ eq(test, 2);
+ cm.removeKeyMap(map1);
+ sendKey(39);
+ eq(test, 12);
+ cm.removeKeyMap(map2);
+ sendKey(39);
+ eq(test, 12);
+ eqCursorPos(cm.getCursor(), Pos(0, 2, "before"));
+ cm.addKeyMap({Right: function() { test = 55; }, name: "mymap"});
+ sendKey(39);
+ eq(test, 55);
+ cm.removeKeyMap("mymap");
+ sendKey(39);
+ eqCursorPos(cm.getCursor(), Pos(0, 3, "before"));
+}, {value: "abc"});
+
+function mouseDown(cm, button, pos, mods) {
+ var coords = cm.charCoords(pos, "window")
+ var event = {type: "mousedown",
+ preventDefault: Math.min,
+ which: button,
+ target: cm.display.lineDiv,
+ clientX: coords.left, clientY: coords.top}
+ if (mods) for (var prop in mods) event[prop] = mods[prop]
+ cm.triggerOnMouseDown(event)
+}
+
+testCM("mouseBinding", function(cm) {
+ var fired = []
+ cm.addKeyMap({
+ "Shift-LeftClick": function(_cm, pos) {
+ eqCharPos(pos, Pos(1, 2))
+ fired.push("a")
+ },
+ "Shift-LeftDoubleClick": function() { fired.push("b") },
+ "Shift-LeftTripleClick": function() { fired.push("c") }
+ })
+
+ function send(button, mods) { mouseDown(cm, button, Pos(1, 2), mods) }
+ send(1, {shiftKey: true})
+ send(1, {shiftKey: true})
+ send(1, {shiftKey: true})
+ send(1, {})
+ send(2, {ctrlKey: true})
+ send(2, {ctrlKey: true})
+ eq(fired.join(" "), "a b c")
+}, {value: "foo\nbar\nbaz"})
+
+testCM("configureMouse", function(cm) {
+ cm.setOption("configureMouse", function() { return {unit: "word"} })
+ mouseDown(cm, 1, Pos(0, 5))
+ eqCharPos(cm.getCursor("from"), Pos(0, 4))
+ eqCharPos(cm.getCursor("to"), Pos(0, 7))
+ cm.setOption("configureMouse", function() { return {extend: true} })
+ mouseDown(cm, 1, Pos(0, 0))
+ eqCharPos(cm.getCursor("from"), Pos(0, 0))
+ eqCharPos(cm.getCursor("to"), Pos(0, 4))
+}, {value: "foo bar baz"})
+
+testCM("findPosH", function(cm) {
+ forEach([{from: Pos(0, 0), to: Pos(0, 1, "before"), by: 1},
+ {from: Pos(0, 0), to: Pos(0, 0), by: -1, hitSide: true},
+ {from: Pos(0, 0), to: Pos(0, 4, "before"), by: 1, unit: "word"},
+ {from: Pos(0, 0), to: Pos(0, 8, "before"), by: 2, unit: "word"},
+ {from: Pos(0, 0), to: Pos(2, 0, "after"), by: 20, unit: "word", hitSide: true},
+ {from: Pos(0, 7), to: Pos(0, 5, "after"), by: -1, unit: "word"},
+ {from: Pos(0, 4), to: Pos(0, 8, "before"), by: 1, unit: "word"},
+ {from: Pos(1, 0), to: Pos(1, 18, "before"), by: 3, unit: "word"},
+ {from: Pos(1, 22), to: Pos(1, 5, "after"), by: -3, unit: "word"},
+ {from: Pos(1, 15), to: Pos(1, 10, "after"), by: -5},
+ {from: Pos(1, 15), to: Pos(1, 10, "after"), by: -5, unit: "column"},
+ {from: Pos(1, 15), to: Pos(1, 0, "after"), by: -50, unit: "column", hitSide: true},
+ {from: Pos(1, 15), to: Pos(1, 24, "before"), by: 50, unit: "column", hitSide: true},
+ {from: Pos(1, 15), to: Pos(2, 0, "after"), by: 50, hitSide: true}], function(t) {
+ var r = cm.findPosH(t.from, t.by, t.unit || "char");
+ eqCursorPos(r, t.to);
+ eq(!!r.hitSide, !!t.hitSide);
+ });
+}, {value: "line one\nline two.something.other\n"});
+
+testCM("beforeChange", function(cm) {
+ cm.on("beforeChange", function(cm, change) {
+ var text = [];
+ for (var i = 0; i < change.text.length; ++i)
+ text.push(change.text[i].replace(/\s/g, "_"));
+ change.update(null, null, text);
+ });
+ cm.setValue("hello, i am a\nnew document\n");
+ eq(cm.getValue(), "hello,_i_am_a\nnew_document\n");
+ CodeMirror.on(cm.getDoc(), "beforeChange", function(doc, change) {
+ if (change.from.line == 0) change.cancel();
+ });
+ cm.setValue("oops"); // Canceled
+ eq(cm.getValue(), "hello,_i_am_a\nnew_document\n");
+ cm.replaceRange("hey hey hey", Pos(1, 0), Pos(2, 0));
+ eq(cm.getValue(), "hello,_i_am_a\nhey_hey_hey");
+}, {value: "abcdefghijk"});
+
+testCM("beforeChangeUndo", function(cm) {
+ cm.replaceRange("hi", Pos(0, 0), Pos(0));
+ cm.replaceRange("bye", Pos(0, 0), Pos(0));
+ eq(cm.historySize().undo, 2);
+ cm.on("beforeChange", function(cm, change) {
+ is(!change.update);
+ change.cancel();
+ });
+ cm.undo();
+ eq(cm.historySize().undo, 0);
+ eq(cm.getValue(), "bye\ntwo");
+}, {value: "one\ntwo"});
+
+testCM("beforeSelectionChange", function(cm) {
+ function notAtEnd(cm, pos) {
+ var len = cm.getLine(pos.line).length;
+ if (!len || pos.ch == len) return Pos(pos.line, pos.ch - 1);
+ return pos;
+ }
+ cm.on("beforeSelectionChange", function(cm, obj) {
+ obj.update([{anchor: notAtEnd(cm, obj.ranges[0].anchor),
+ head: notAtEnd(cm, obj.ranges[0].head)}]);
+ });
+
+ addDoc(cm, 10, 10);
+ cm.execCommand("goLineEnd");
+ eqCursorPos(cm.getCursor(), Pos(0, 9));
+ cm.execCommand("selectAll");
+ eqCursorPos(cm.getCursor("start"), Pos(0, 0));
+ eqCursorPos(cm.getCursor("end"), Pos(9, 9));
+});
+
+testCM("change_removedText", function(cm) {
+ cm.setValue("abc\ndef");
+
+ var removedText = [];
+ cm.on("change", function(cm, change) {
+ removedText.push(change.removed);
+ });
+
+ cm.operation(function() {
+ cm.replaceRange("xyz", Pos(0, 0), Pos(1,1));
+ cm.replaceRange("123", Pos(0,0));
+ });
+
+ eq(removedText.length, 2);
+ eq(removedText[0].join("\n"), "abc\nd");
+ eq(removedText[1].join("\n"), "");
+
+ var removedText = [];
+ cm.undo();
+ eq(removedText.length, 2);
+ eq(removedText[0].join("\n"), "123");
+ eq(removedText[1].join("\n"), "xyz");
+
+ var removedText = [];
+ cm.redo();
+ eq(removedText.length, 2);
+ eq(removedText[0].join("\n"), "abc\nd");
+ eq(removedText[1].join("\n"), "");
+});
+
+testCM("lineStyleFromMode", function(cm) {
+ CodeMirror.defineMode("test_mode", function() {
+ return {token: function(stream) {
+ if (stream.match(/^\[[^\]]*\]/)) return " line-brackets ";
+ if (stream.match(/^\([^\)]*\)/)) return " line-background-parens ";
+ if (stream.match(/^<[^>]*>/)) return " span line-line line-background-bg ";
+ stream.match(/^\s+|^\S+/);
+ }};
+ });
+ cm.setOption("mode", "test_mode");
+ var bracketElts = byClassName(cm.getWrapperElement(), "brackets");
+ eq(bracketElts.length, 1, "brackets count");
+ eq(bracketElts[0].nodeName, "PRE");
+ is(!/brackets.*brackets/.test(bracketElts[0].className));
+ var parenElts = byClassName(cm.getWrapperElement(), "parens");
+ eq(parenElts.length, 1, "parens count");
+ eq(parenElts[0].nodeName, "DIV");
+ is(!/parens.*parens/.test(parenElts[0].className));
+ eq(parenElts[0].parentElement.nodeName, "DIV");
+
+ is(byClassName(cm.getWrapperElement(), "bg").length > 0);
+ is(byClassName(cm.getWrapperElement(), "line").length > 0);
+ var spanElts = byClassName(cm.getWrapperElement(), "cm-span");
+ eq(spanElts.length, 2);
+ is(/^\s*cm-span\s*$/.test(spanElts[0].className));
+}, {value: "line1: [br] [br]\nline2: (par) (par)\nline3: <tag> <tag>"});
+
+testCM("lineStyleFromBlankLine", function(cm) {
+ CodeMirror.defineMode("lineStyleFromBlankLine_mode", function() {
+ return {token: function(stream) { stream.skipToEnd(); return "comment"; },
+ blankLine: function() { return "line-blank"; }};
+ });
+ cm.setOption("mode", "lineStyleFromBlankLine_mode");
+ var blankElts = byClassName(cm.getWrapperElement(), "blank");
+ eq(blankElts.length, 1);
+ eq(blankElts[0].nodeName, "PRE");
+ cm.replaceRange("x", Pos(1, 0));
+ blankElts = byClassName(cm.getWrapperElement(), "blank");
+ eq(blankElts.length, 0);
+}, {value: "foo\n\nbar"});
+
+CodeMirror.registerHelper("xxx", "a", "A");
+CodeMirror.registerHelper("xxx", "b", "B");
+CodeMirror.defineMode("yyy", function() {
+ return {
+ token: function(stream) { stream.skipToEnd(); },
+ xxx: ["a", "b", "q"]
+ };
+});
+CodeMirror.registerGlobalHelper("xxx", "c", function(m) { return m.enableC; }, "C");
+
+testCM("helpers", function(cm) {
+ cm.setOption("mode", "yyy");
+ eq(cm.getHelpers(Pos(0, 0), "xxx").join("/"), "A/B");
+ cm.setOption("mode", {name: "yyy", modeProps: {xxx: "b", enableC: true}});
+ eq(cm.getHelpers(Pos(0, 0), "xxx").join("/"), "B/C");
+ cm.setOption("mode", "javascript");
+ eq(cm.getHelpers(Pos(0, 0), "xxx").join("/"), "");
+});
+
+testCM("selectionHistory", function(cm) {
+ for (var i = 0; i < 3; i++) {
+ cm.setExtending(true);
+ cm.execCommand("goCharRight");
+ cm.setExtending(false);
+ cm.execCommand("goCharRight");
+ cm.execCommand("goCharRight");
+ }
+ cm.execCommand("undoSelection");
+ eq(cm.getSelection(), "c");
+ cm.execCommand("undoSelection");
+ eq(cm.getSelection(), "");
+ eqCursorPos(cm.getCursor(), Pos(0, 4, "before"));
+ cm.execCommand("undoSelection");
+ eq(cm.getSelection(), "b");
+ cm.execCommand("redoSelection");
+ eq(cm.getSelection(), "");
+ eqCursorPos(cm.getCursor(), Pos(0, 4, "before"));
+ cm.execCommand("redoSelection");
+ eq(cm.getSelection(), "c");
+ cm.execCommand("redoSelection");
+ eq(cm.getSelection(), "");
+ eqCursorPos(cm.getCursor(), Pos(0, 6, "before"));
+}, {value: "a b c d"});
+
+testCM("selectionChangeReducesRedo", function(cm) {
+ cm.replaceSelection("X");
+ cm.execCommand("goCharRight");
+ cm.undoSelection();
+ cm.execCommand("selectAll");
+ cm.undoSelection();
+ eq(cm.getValue(), "Xabc");
+ eqCursorPos(cm.getCursor(), Pos(0, 1));
+ cm.undoSelection();
+ eq(cm.getValue(), "abc");
+}, {value: "abc"});
+
+testCM("selectionHistoryNonOverlapping", function(cm) {
+ cm.setSelection(Pos(0, 0), Pos(0, 1));
+ cm.setSelection(Pos(0, 2), Pos(0, 3));
+ cm.execCommand("undoSelection");
+ eqCursorPos(cm.getCursor("anchor"), Pos(0, 0));
+ eqCursorPos(cm.getCursor("head"), Pos(0, 1));
+}, {value: "1234"});
+
+testCM("cursorMotionSplitsHistory", function(cm) {
+ cm.replaceSelection("a");
+ cm.execCommand("goCharRight");
+ cm.replaceSelection("b");
+ cm.replaceSelection("c");
+ cm.undo();
+ eq(cm.getValue(), "a1234");
+ eqCursorPos(cm.getCursor(), Pos(0, 2, "before"));
+ cm.undo();
+ eq(cm.getValue(), "1234");
+ eqCursorPos(cm.getCursor(), Pos(0, 0));
+}, {value: "1234"});
+
+testCM("selChangeInOperationDoesNotSplit", function(cm) {
+ for (var i = 0; i < 4; i++) {
+ cm.operation(function() {
+ cm.replaceSelection("x");
+ cm.setCursor(Pos(0, cm.getCursor().ch - 1));
+ });
+ }
+ eqCursorPos(cm.getCursor(), Pos(0, 0));
+ eq(cm.getValue(), "xxxxa");
+ cm.undo();
+ eq(cm.getValue(), "a");
+}, {value: "a"});
+
+testCM("alwaysMergeSelEventWithChangeOrigin", function(cm) {
+ cm.replaceSelection("U", null, "foo");
+ cm.setSelection(Pos(0, 0), Pos(0, 1), {origin: "foo"});
+ cm.undoSelection();
+ eq(cm.getValue(), "a");
+ cm.replaceSelection("V", null, "foo");
+ cm.setSelection(Pos(0, 0), Pos(0, 1), {origin: "bar"});
+ cm.undoSelection();
+ eq(cm.getValue(), "Va");
+}, {value: "a"});
+
+testCM("getTokenAt", function(cm) {
+ var tokPlus = cm.getTokenAt(Pos(0, 2));
+ eq(tokPlus.type, "operator");
+ eq(tokPlus.string, "+");
+ var toks = cm.getLineTokens(0);
+ eq(toks.length, 3);
+ forEach([["number", "1"], ["operator", "+"], ["number", "2"]], function(expect, i) {
+ eq(toks[i].type, expect[0]);
+ eq(toks[i].string, expect[1]);
+ });
+}, {value: "1+2", mode: "javascript"});
+
+testCM("getTokenTypeAt", function(cm) {
+ eq(cm.getTokenTypeAt(Pos(0, 0)), "number");
+ eq(cm.getTokenTypeAt(Pos(0, 6)), "string");
+ cm.addOverlay({
+ token: function(stream) {
+ if (stream.match("foo")) return "foo";
+ else stream.next();
+ }
+ });
+ eq(byClassName(cm.getWrapperElement(), "cm-foo").length, 1);
+ eq(cm.getTokenTypeAt(Pos(0, 6)), "string");
+}, {value: "1 + 'foo'", mode: "javascript"});
+
+testCM("addOverlay", function(cm) {
+ cm.addOverlay({
+ token: function(stream) {
+ var base = stream.baseToken()
+ if (!/comment/.test(base.type) && stream.match(/\d+/)) return "x"
+ stream.next()
+ }
+ })
+ var x = byClassName(cm.getWrapperElement(), "cm-x")
+ is(x.length, 1)
+ is(x[0].textContent, "233")
+ cm.replaceRange("", Pos(0, 4), Pos(0, 6))
+ is(byClassName(cm.getWrapperElement(), "cm-x").length, 2)
+}, {value: "foo /* 100 */\nbar + 233;\nbaz", mode: "javascript"})
+
+testCM("resizeLineWidget", function(cm) {
+ addDoc(cm, 200, 3);
+ var widget = document.createElement("pre");
+ widget.innerHTML = "imwidget";
+ widget.style.background = "yellow";
+ cm.addLineWidget(1, widget, {noHScroll: true});
+ cm.setSize(40);
+ is(widget.parentNode.offsetWidth < 42);
+});
+
+testCM("combinedOperations", function(cm) {
+ var place = document.getElementById("testground");
+ var other = CodeMirror(place, {value: "123"});
+ try {
+ cm.operation(function() {
+ cm.addLineClass(0, "wrap", "foo");
+ other.addLineClass(0, "wrap", "foo");
+ });
+ eq(byClassName(cm.getWrapperElement(), "foo").length, 1);
+ eq(byClassName(other.getWrapperElement(), "foo").length, 1);
+ cm.operation(function() {
+ cm.removeLineClass(0, "wrap", "foo");
+ other.removeLineClass(0, "wrap", "foo");
+ });
+ eq(byClassName(cm.getWrapperElement(), "foo").length, 0);
+ eq(byClassName(other.getWrapperElement(), "foo").length, 0);
+ } finally {
+ place.removeChild(other.getWrapperElement());
+ }
+}, {value: "abc"});
+
+testCM("eventOrder", function(cm) {
+ var seen = [];
+ cm.on("change", function() {
+ if (!seen.length) cm.replaceSelection(".");
+ seen.push("change");
+ });
+ cm.on("cursorActivity", function() {
+ cm.replaceSelection("!");
+ seen.push("activity");
+ });
+ cm.replaceSelection("/");
+ eq(seen.join(","), "change,change,activity,change");
+});
+
+testCM("splitSpaces_nonspecial", function(cm) {
+ eq(byClassName(cm.getWrapperElement(), "cm-invalidchar").length, 0);
+}, {
+ specialChars: /[\u00a0]/,
+ value: "spaces -> <- between"
+});
+
+test("core_rmClass", function() {
+ var node = document.createElement("div");
+ node.className = "foo-bar baz-quux yadda";
+ CodeMirror.rmClass(node, "quux");
+ eq(node.className, "foo-bar baz-quux yadda");
+ CodeMirror.rmClass(node, "baz-quux");
+ eq(node.className, "foo-bar yadda");
+ CodeMirror.rmClass(node, "yadda");
+ eq(node.className, "foo-bar");
+ CodeMirror.rmClass(node, "foo-bar");
+ eq(node.className, "");
+ node.className = " foo ";
+ CodeMirror.rmClass(node, "foo");
+ eq(node.className, "");
+});
+
+test("core_addClass", function() {
+ var node = document.createElement("div");
+ CodeMirror.addClass(node, "a");
+ eq(node.className, "a");
+ CodeMirror.addClass(node, "a");
+ eq(node.className, "a");
+ CodeMirror.addClass(node, "b");
+ eq(node.className, "a b");
+ CodeMirror.addClass(node, "a");
+ CodeMirror.addClass(node, "b");
+ eq(node.className, "a b");
+});
+
+testCM("lineSeparator", function(cm) {
+ eq(cm.lineCount(), 3);
+ eq(cm.getLine(1), "bar\r");
+ eq(cm.getLine(2), "baz\rquux");
+ cm.setOption("lineSeparator", "\r");
+ eq(cm.lineCount(), 5);
+ eq(cm.getLine(4), "quux");
+ eq(cm.getValue(), "foo\rbar\r\rbaz\rquux");
+ eq(cm.getValue("\n"), "foo\nbar\n\nbaz\nquux");
+ cm.setOption("lineSeparator", null);
+ cm.setValue("foo\nbar\r\nbaz\rquux");
+ eq(cm.lineCount(), 4);
+}, {value: "foo\nbar\r\nbaz\rquux",
+ lineSeparator: "\n"});
+
+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]/
+var getChar = function (noExtending) { var res; do {res = String.fromCharCode(Math.floor(Math.random()*0x8ac)); } while ([0x90].indexOf(res.charCodeAt(0)) != -1 || (noExtending && extendingChars.test(res))); return res }
+var getString = function (n) { var res = getChar(true); while (--n > 0) res += getChar(); return res }
+
+function makeItWrapAfter(cm, pos) {
+ var firstLineTop = cm.cursorCoords(Pos(0, 0)).top;
+ for(var w = 0, posTop; posTop != firstLineTop; ++w) {
+ cm.setSize(w);
+ posTop = cm.charCoords(pos).top;
+ }
+}
+
+function countIf(arr, f) {
+ var result = 0
+ for (var i = 0; i < arr.length; i++) if (f[arr[i]]) result++
+ return result
+}
+
+function testMoveBidi(str) {
+ testCM("move_bidi_" + str, function(cm) {
+ if (cm.getOption("inputStyle") != "textarea" || !cm.getOption("rtlMoveVisually")) return;
+ cm.getScrollerElement().style.fontFamily = "monospace";
+ makeItWrapAfter(cm, Pos(0, 5));
+
+ var steps = str.length - countIf(str.split(""), function(ch) { return extendingChars.test(ch) });
+ var lineBreaks = {}
+ lineBreaks[6 - countIf(str.substr(0, 5).split(""), function(ch) { return extendingChars.test(ch) })] = 'w';
+ if (str.indexOf("\n") != -1) {
+ lineBreaks[steps - 2] = 'n';
+ }
+
+ // Make sure we are at the visual beginning of the first line
+ cm.execCommand("goLineStart");
+
+ var prevCoords = cm.cursorCoords(), coords;
+ for(var i = 0; i < steps; ++i) {
+ cm.execCommand("goCharRight");
+ coords = cm.cursorCoords();
+ if ((i >= 10 && i <= 12) && !lineBreaks[i] && coords.left < prevCoords.left && coords.top > prevCoords.top) {
+ // The first line wraps twice
+ lineBreaks[i] = 'w';
+ }
+ if (!lineBreaks[i]) {
+ is(coords.left > prevCoords.left, "In step " + i + ", cursor didn't move right");
+ eq(coords.top, prevCoords.top, "In step " + i + ", cursor moved out of line");
+ } else {
+ is(coords.left < prevCoords.left, i);
+ is(coords.top > prevCoords.top, i);
+ }
+ prevCoords = coords;
+ }
+
+ cm.execCommand("goCharRight");
+ coords = cm.cursorCoords();
+ eq(coords.left, prevCoords.left, "Moving " + steps + " steps right didn't reach the end");
+ eq(coords.top, prevCoords.top, "Moving " + steps + " steps right didn't reach the end");
+
+ for(i = steps - 1; i >= 0; --i) {
+ cm.execCommand("goCharLeft");
+ coords = cm.cursorCoords();
+ if (!(lineBreaks[i] == 'n' || lineBreaks[i + 1] == 'w')) {
+ is(coords.left < prevCoords.left, "In step " + i + ", cursor didn't move left");
+ eq(coords.top, prevCoords.top, "In step " + i + ", cursor is not at the same line anymore");
+ } else {
+ is(coords.left > prevCoords.left, i);
+ is(coords.top < prevCoords.top, i);
+ }
+ prevCoords = coords;
+ }
+
+ cm.execCommand("goCharLeft");
+ coords = cm.cursorCoords();
+ eq(coords.left, prevCoords.left, "Moving " + steps + " steps left didn't reach the beginning");
+ eq(coords.top, prevCoords.top, "Moving " + steps + " steps left didn't reach the beginning");
+ }, {value: str, lineWrapping: true})
+};
+
+function testMoveEndBidi(str) {
+ testCM("move_end_bidi_" + str, function(cm) {
+ cm.getScrollerElement().style.fontFamily = "monospace";
+ makeItWrapAfter(cm, Pos(0, 5));
+
+ cm.execCommand("goLineStart");
+ var pos = cm.doc.getCursor();
+ cm.execCommand("goCharLeft");
+ eqCursorPos(pos, cm.doc.getCursor());
+
+ cm.execCommand("goLineEnd");
+ pos = cm.doc.getCursor();
+ cm.execCommand("goColumnRight");
+ eqCursorPos(pos, cm.doc.getCursor());
+ }, {value: str, lineWrapping: true})
+};
+
+var bidiTests = [];
+
+// We don't correctly implement L1 UBA
+// See https://bugzilla.mozilla.org/show_bug.cgi?id=1331501
+// and https://bugs.chromium.org/p/chromium/issues/detail?id=673405
+/*
+bidiTests.push("Say ا ب جabj\nS");
+bidiTests.push("Sayyy ا ا ب ج");
+*/
+
+if (!phantom) {
+ bidiTests.push("Όȝǝڪȉۥ״ۺ׆ɀҩۏ\nҳ");
+ bidiTests.push("ŌӰтقȤ؁ƥ؅٣ĎȺ١\nϚ");
+ bidiTests.push("ٻоҤѕѽΩ־؉ïίքdz\nٵ");
+ bidiTests.push("؅؁ĆՕƿɁǞϮؠȩóć\nď");
+ bidiTests.push("RŨďңŪzϢŎƏԖڇڦ\nӈ");
+ bidiTests.push("ό׊۷٢ԜһОצЉيčǟ\nѩ");
+ bidiTests.push("ۑÚҳҕڬġڹհяųKV\nr");
+ bidiTests.push("źڻғúہ4ם1Ƞc1a\nԁ");
+ bidiTests.push("ҒȨҟփƞ٦ԓȦڰғâƥ\nڤ");
+ bidiTests.push("ϖسՉȏŧΔԛdžĎӟیڡ\nέ");
+ bidiTests.push("۹ؼL۵ĺȧКԙػא7״\nم");
+ bidiTests.push("ن (ي)\u2009أقواس"); // thin space to throw off Firefox 51's broken white-space compressing behavior
+}
+
+bidiTests.push("քմѧǮßپüŢҍҞўڳ\nӧ");
+
+//bidiTests.push("Count ١ ٢ ٣ ٤");
+//bidiTests.push("ӣאƦϰ؊ȓېÛوը٬ز\nϪ");
+//bidiTests.push("ҾճٳџIՖӻ٥׭֐؜ڏ\nێ");
+//bidiTests.push("ҬÓФ؜ڂį٦Ͽɓڐͳٵ\nՈ");
+//bidiTests.push("aѴNijȻهˇ҃ڱӧǻֵ\na");
+//bidiTests.push(" a٧ا٢ ب جa\nS");
+
+for (var i = 0; i < bidiTests.length; ++i) {
+ testMoveBidi(bidiTests[i]);
+ testMoveEndBidi(bidiTests[i]);
+}
+
+/*
+for (var i = 0; i < 5; ++i) {
+ testMoveBidi(getString(12) + "\n" + getString(1));
+}
+*/
+
+function testCoordsWrappedBidi(str) {
+ testCM("coords_wrapped_bidi_" + str, function(cm) {
+ cm.getScrollerElement().style.fontFamily = "monospace";
+ makeItWrapAfter(cm, Pos(0, 5));
+
+ // Make sure we are at the visual beginning of the first line
+ var pos = Pos(0, 0), lastPos;
+ cm.doc.setCursor(pos);
+ do {
+ lastPos = pos;
+ cm.execCommand("goCharLeft");
+ pos = cm.doc.getCursor();
+ } while (pos != lastPos)
+
+ var top = cm.charCoords(Pos(0, 0)).top, lastTop;
+ for (var i = 1; i < str.length; ++i) {
+ lastTop = top;
+ top = cm.charCoords(Pos(0, i)).top;
+ is(top >= lastTop);
+ }
+ }, {value: str, lineWrapping: true})
+};
+
+testCoordsWrappedBidi("Count ١ ٢ ٣ ٤");
+/*
+for (var i = 0; i < 5; ++i) {
+ testCoordsWrappedBidi(getString(50));
+}
+*/
+
+testCM("rtl_wrapped_selection", function(cm) {
+ cm.setSelection(Pos(0, 10), Pos(0, 190))
+ is(byClassName(cm.getWrapperElement(), "CodeMirror-selected").length >= 3)
+}, {value: new Array(10).join(" فتي تم تضمينها فتي تم"), lineWrapping: true})
+
+testCM("bidi_wrapped_selection", function(cm) {
+ if (phantom) return
+ cm.setSize(cm.charCoords(Pos(0, 10), "editor").left)
+ cm.setSelection(Pos(0, 37), Pos(0, 80))
+ var blocks = byClassName(cm.getWrapperElement(), "CodeMirror-selected")
+ is(blocks.length >= 2)
+ is(blocks.length <= 3)
+ var boxTop = blocks[0].getBoundingClientRect(), boxBot = blocks[blocks.length - 1].getBoundingClientRect()
+ is(boxTop.left > cm.charCoords(Pos(0, 1)).right)
+ is(boxBot.right < cm.charCoords(Pos(0, cm.getLine(0).length - 2)).left)
+}, {value: "<p>مفتي11 تم تضمينهفتي تم تضمينها فتي تفتي تم تضمينها فتي تفتي تم تضمينها فتي تفتي تم تضمينها فتي تا فت10ي ت</p>", lineWrapping: true})
+
+testCM("delete_wrapped", function(cm) {
+ makeItWrapAfter(cm, Pos(0, 2));
+ cm.doc.setCursor(Pos(0, 3, "after"));
+ cm.deleteH(-1, "char");
+ eq(cm.getLine(0), "1245");
+}, {value: "12345", lineWrapping: true})
+
+testCM("issue_4878", function(cm) {
+ if (phantom) return
+ cm.setCursor(Pos(1, 12, "after"));
+ cm.moveH(-1, "char");
+ eqCursorPos(cm.getCursor(), Pos(0, 113, "before"));
+}, {value: " في تطبيق السمات مرة واحدة https://github.com/codemirror/CodeMirror/issues/4878#issuecomment-330550964على سبيل المثال <code>\"foo bar\"</code>\n" +
+" سيتم تعيين", direction: "rtl", lineWrapping: true});
+
+CodeMirror.defineMode("lookahead_mode", function() {
+ // Colors text as atom if the line two lines down has an x in it
+ return {
+ token: function(stream) {
+ stream.skipToEnd()
+ return /x/.test(stream.lookAhead(2)) ? "atom" : null
+ }
+ }
+})
+
+testCM("mode_lookahead", function(cm) {
+ eq(cm.getTokenAt(Pos(0, 1)).type, "atom")
+ eq(cm.getTokenAt(Pos(1, 1)).type, "atom")
+ eq(cm.getTokenAt(Pos(2, 1)).type, null)
+ cm.replaceRange("\n", Pos(2, 0))
+ eq(cm.getTokenAt(Pos(0, 1)).type, null)
+ eq(cm.getTokenAt(Pos(1, 1)).type, "atom")
+}, {value: "foo\na\nx\nx\n", mode: "lookahead_mode"})
diff --git a/devtools/client/shared/sourceeditor/test/codemirror/vim_test.js b/devtools/client/shared/sourceeditor/test/codemirror/vim_test.js
new file mode 100644
index 0000000000..72a9896b59
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/codemirror/vim_test.js
@@ -0,0 +1,4729 @@
+var Pos = CodeMirror.Pos;
+CodeMirror.Vim.suppressErrorLogging = true;
+
+var code = '' +
+' wOrd1 (#%\n' +
+' word3] \n' +
+'aopop pop 0 1 2 3 4\n' +
+' (a) [b] {c} \n' +
+'int getchar(void) {\n' +
+' static char buf[BUFSIZ];\n' +
+' static char *bufp = buf;\n' +
+' if (n == 0) { /* buffer is empty */\n' +
+' n = read(0, buf, sizeof buf);\n' +
+' bufp = buf;\n' +
+' }\n' +
+'\n' +
+' return (--n >= 0) ? (unsigned char) *bufp++ : EOF;\n' +
+' \n' +
+'}\n';
+
+var lines = (function() {
+ lineText = code.split('\n');
+ var ret = [];
+ for (var i = 0; i < lineText.length; i++) {
+ ret[i] = {
+ line: i,
+ length: lineText[i].length,
+ lineText: lineText[i],
+ textStart: /^\s*/.exec(lineText[i])[0].length
+ };
+ }
+ return ret;
+})();
+var endOfDocument = makeCursor(lines.length - 1,
+ lines[lines.length - 1].length);
+var wordLine = lines[0];
+var bigWordLine = lines[1];
+var charLine = lines[2];
+var bracesLine = lines[3];
+var seekBraceLine = lines[4];
+
+var word1 = {
+ start: new Pos(wordLine.line, 1),
+ end: new Pos(wordLine.line, 5)
+};
+var word2 = {
+ start: new Pos(wordLine.line, word1.end.ch + 2),
+ end: new Pos(wordLine.line, word1.end.ch + 4)
+};
+var word3 = {
+ start: new Pos(bigWordLine.line, 1),
+ end: new Pos(bigWordLine.line, 5)
+};
+var bigWord1 = word1;
+var bigWord2 = word2;
+var bigWord3 = {
+ start: new Pos(bigWordLine.line, 1),
+ end: new Pos(bigWordLine.line, 7)
+};
+var bigWord4 = {
+ start: new Pos(bigWordLine.line, bigWord1.end.ch + 3),
+ end: new Pos(bigWordLine.line, bigWord1.end.ch + 7)
+};
+
+var oChars = [ new Pos(charLine.line, 1),
+ new Pos(charLine.line, 3),
+ new Pos(charLine.line, 7) ];
+var pChars = [ new Pos(charLine.line, 2),
+ new Pos(charLine.line, 4),
+ new Pos(charLine.line, 6),
+ new Pos(charLine.line, 8) ];
+var numChars = [ new Pos(charLine.line, 10),
+ new Pos(charLine.line, 12),
+ new Pos(charLine.line, 14),
+ new Pos(charLine.line, 16),
+ new Pos(charLine.line, 18)];
+var parens1 = {
+ start: new Pos(bracesLine.line, 1),
+ end: new Pos(bracesLine.line, 3)
+};
+var squares1 = {
+ start: new Pos(bracesLine.line, 5),
+ end: new Pos(bracesLine.line, 7)
+};
+var curlys1 = {
+ start: new Pos(bracesLine.line, 9),
+ end: new Pos(bracesLine.line, 11)
+};
+var seekOutside = {
+ start: new Pos(seekBraceLine.line, 1),
+ end: new Pos(seekBraceLine.line, 16)
+};
+var seekInside = {
+ start: new Pos(seekBraceLine.line, 14),
+ end: new Pos(seekBraceLine.line, 11)
+};
+
+function copyCursor(cur) {
+ return new Pos(cur.line, cur.ch);
+}
+
+function forEach(arr, func) {
+ for (var i = 0; i < arr.length; i++) {
+ func(arr[i], i, arr);
+ }
+}
+
+function expectFail(fn) {
+ try {
+ fn();
+ } catch(expected) {
+ return;
+ };
+ throw new Error("Expected to throw an error");
+}
+
+function testVim(name, run, opts, expectedFail) {
+ var vimOpts = {
+ lineNumbers: true,
+ vimMode: true,
+ showCursorWhenSelecting: true,
+ value: code
+ };
+ for (var prop in opts) {
+ if (opts.hasOwnProperty(prop)) {
+ vimOpts[prop] = opts[prop];
+ }
+ }
+ return test('vim_' + name, function() {
+ var place = document.getElementById("testground");
+ var cm = CodeMirror(place, vimOpts);
+ var vim = CodeMirror.Vim.maybeInitVimState_(cm);
+
+ function doKeysFn(cm) {
+ return function(args) {
+ if (args instanceof Array) {
+ arguments = args;
+ }
+ for (var i = 0; i < arguments.length; i++) {
+ var result = CodeMirror.Vim.handleKey(cm, arguments[i]);
+ if (!result && cm.state.vim.insertMode) {
+ cm.replaceSelections(fillArray(arguments[i], cm.listSelections().length));
+ }
+ }
+ }
+ }
+ function doInsertModeKeysFn(cm) {
+ return function(args) {
+ if (args instanceof Array) { arguments = args; }
+ function executeHandler(handler) {
+ if (typeof handler == 'string') {
+ CodeMirror.commands[handler](cm);
+ } else {
+ handler(cm);
+ }
+ return true;
+ }
+ for (var i = 0; i < arguments.length; i++) {
+ var key = arguments[i];
+ // Find key in keymap and handle.
+ var handled = CodeMirror.lookupKey(key, cm.getOption('keyMap'), executeHandler, cm);
+ // Record for insert mode.
+ if (handled == "handled" && cm.state.vim.insertMode && arguments[i] != 'Esc') {
+ var lastChange = CodeMirror.Vim.getVimGlobalState_().macroModeState.lastInsertModeChanges;
+ if (lastChange && (key.indexOf('Delete') != -1 || key.indexOf('Backspace') != -1)) {
+ lastChange.changes.push(new CodeMirror.Vim.InsertModeKey(key));
+ }
+ }
+ }
+ }
+ }
+ function doExFn(cm) {
+ return function(command) {
+ cm.openDialog = helpers.fakeOpenDialog(command);
+ helpers.doKeys(':');
+ }
+ }
+ function assertCursorAtFn(cm) {
+ return function(line, ch) {
+ var pos;
+ if (ch == null && typeof line.line == 'number') {
+ pos = line;
+ } else {
+ pos = makeCursor(line, ch);
+ }
+ eqCursorPos(cm.getCursor(), pos);
+ }
+ }
+ function fakeOpenDialog(result) {
+ return function(text, callback) {
+ return callback(result);
+ }
+ }
+ function fakeOpenNotification(matcher) {
+ return function(text) {
+ matcher(text);
+ }
+ }
+ var helpers = {
+ doKeys: doKeysFn(cm),
+ // Warning: Only emulates keymap events, not character insertions. Use
+ // replaceRange to simulate character insertions.
+ // Keys are in CodeMirror format, NOT vim format.
+ doInsertModeKeys: doInsertModeKeysFn(cm),
+ doEx: doExFn(cm),
+ assertCursorAt: assertCursorAtFn(cm),
+ fakeOpenDialog: fakeOpenDialog,
+ fakeOpenNotification: fakeOpenNotification,
+ getRegisterController: function() {
+ return CodeMirror.Vim.getRegisterController();
+ }
+ }
+ CodeMirror.Vim.resetVimGlobalState_();
+ var successful = false;
+ var savedOpenNotification = cm.openNotification;
+ var savedOpenDialog = cm.openDialog;
+ try {
+ run(cm, vim, helpers);
+ successful = true;
+ } finally {
+ cm.openNotification = savedOpenNotification;
+ cm.openDialog = savedOpenDialog;
+ if (!successful || verbose) {
+ place.style.visibility = "visible";
+ } else {
+ place.removeChild(cm.getWrapperElement());
+ }
+ }
+ }, expectedFail);
+};
+testVim('qq@q', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('q', 'q', 'l', 'l', 'q');
+ helpers.assertCursorAt(0,2);
+ helpers.doKeys('@', 'q');
+ helpers.assertCursorAt(0,4);
+}, { value: ' '});
+testVim('@@', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('q', 'q', 'l', 'l', 'q');
+ helpers.assertCursorAt(0,2);
+ helpers.doKeys('@', 'q');
+ helpers.assertCursorAt(0,4);
+ helpers.doKeys('@', '@');
+ helpers.assertCursorAt(0,6);
+}, { value: ' '});
+var jumplistScene = ''+
+ 'word\n'+
+ '(word)\n'+
+ '{word\n'+
+ 'word.\n'+
+ '\n'+
+ 'word search\n'+
+ '}word\n'+
+ 'word\n'+
+ 'word\n';
+function testJumplist(name, keys, endPos, startPos, dialog) {
+ endPos = makeCursor(endPos[0], endPos[1]);
+ startPos = makeCursor(startPos[0], startPos[1]);
+ testVim(name, function(cm, vim, helpers) {
+ CodeMirror.Vim.resetVimGlobalState_();
+ if(dialog)cm.openDialog = helpers.fakeOpenDialog('word');
+ cm.setCursor(startPos);
+ helpers.doKeys.apply(null, keys);
+ helpers.assertCursorAt(endPos);
+ }, {value: jumplistScene});
+}
+testJumplist('jumplist_H', ['H', '<C-o>'], [5,2], [5,2]);
+testJumplist('jumplist_M', ['M', '<C-o>'], [2,2], [2,2]);
+testJumplist('jumplist_L', ['L', '<C-o>'], [2,2], [2,2]);
+testJumplist('jumplist_[[', ['[', '[', '<C-o>'], [5,2], [5,2]);
+testJumplist('jumplist_]]', [']', ']', '<C-o>'], [2,2], [2,2]);
+testJumplist('jumplist_G', ['G', '<C-o>'], [5,2], [5,2]);
+testJumplist('jumplist_gg', ['g', 'g', '<C-o>'], [5,2], [5,2]);
+testJumplist('jumplist_%', ['%', '<C-o>'], [1,5], [1,5]);
+testJumplist('jumplist_{', ['{', '<C-o>'], [1,5], [1,5]);
+testJumplist('jumplist_}', ['}', '<C-o>'], [1,5], [1,5]);
+testJumplist('jumplist_\'', ['m', 'a', 'h', '\'', 'a', 'h', '<C-i>'], [1,0], [1,5]);
+testJumplist('jumplist_`', ['m', 'a', 'h', '`', 'a', 'h', '<C-i>'], [1,5], [1,5]);
+testJumplist('jumplist_*_cachedCursor', ['*', '<C-o>'], [1,3], [1,3]);
+testJumplist('jumplist_#_cachedCursor', ['#', '<C-o>'], [1,3], [1,3]);
+testJumplist('jumplist_n', ['#', 'n', '<C-o>'], [1,1], [2,3]);
+testJumplist('jumplist_N', ['#', 'N', '<C-o>'], [1,1], [2,3]);
+testJumplist('jumplist_repeat_<c-o>', ['*', '*', '*', '3', '<C-o>'], [2,3], [2,3]);
+testJumplist('jumplist_repeat_<c-i>', ['*', '*', '*', '3', '<C-o>', '2', '<C-i>'], [5,0], [2,3]);
+testJumplist('jumplist_repeated_motion', ['3', '*', '<C-o>'], [2,3], [2,3]);
+testJumplist('jumplist_/', ['/', '<C-o>'], [2,3], [2,3], 'dialog');
+testJumplist('jumplist_?', ['?', '<C-o>'], [2,3], [2,3], 'dialog');
+testJumplist('jumplist_skip_deleted_mark<c-o>',
+ ['*', 'n', 'n', 'k', 'd', 'k', '<C-o>', '<C-o>', '<C-o>'],
+ [0,2], [0,2]);
+testJumplist('jumplist_skip_deleted_mark<c-i>',
+ ['*', 'n', 'n', 'k', 'd', 'k', '<C-o>', '<C-i>', '<C-i>'],
+ [1,0], [0,2]);
+
+/**
+ * @param name Name of the test
+ * @param keys An array of keys or a string with a single key to simulate.
+ * @param endPos The expected end position of the cursor.
+ * @param startPos The position the cursor should start at, defaults to 0, 0.
+ */
+function testMotion(name, keys, endPos, startPos) {
+ testVim(name, function(cm, vim, helpers) {
+ if (!startPos) {
+ startPos = new Pos(0, 0);
+ }
+ cm.setCursor(startPos);
+ helpers.doKeys(keys);
+ helpers.assertCursorAt(endPos);
+ });
+}
+
+function makeCursor(line, ch) {
+ return new Pos(line, ch);
+}
+
+function offsetCursor(cur, offsetLine, offsetCh) {
+ return new Pos(cur.line + offsetLine, cur.ch + offsetCh);
+}
+
+// Motion tests
+testMotion('|', '|', makeCursor(0, 0), makeCursor(0,4));
+testMotion('|_repeat', ['3', '|'], makeCursor(0, 2), makeCursor(0,4));
+testMotion('h', 'h', makeCursor(0, 0), word1.start);
+testMotion('h_repeat', ['3', 'h'], offsetCursor(word1.end, 0, -3), word1.end);
+testMotion('l', 'l', makeCursor(0, 1));
+testMotion('l_repeat', ['2', 'l'], makeCursor(0, 2));
+testMotion('j', 'j', offsetCursor(word1.end, 1, 0), word1.end);
+testMotion('j_repeat', ['2', 'j'], offsetCursor(word1.end, 2, 0), word1.end);
+testMotion('j_repeat_clip', ['1000', 'j'], endOfDocument);
+testMotion('k', 'k', offsetCursor(word3.end, -1, 0), word3.end);
+testMotion('k_repeat', ['2', 'k'], makeCursor(0, 4), makeCursor(2, 4));
+testMotion('k_repeat_clip', ['1000', 'k'], makeCursor(0, 4), makeCursor(2, 4));
+testMotion('w', 'w', word1.start);
+testMotion('keepHPos', ['5', 'j', 'j', '7', 'k'], makeCursor(8, 12), makeCursor(12, 12));
+testMotion('keepHPosEol', ['$', '2', 'j'], makeCursor(2, 18));
+testMotion('w_multiple_newlines_no_space', 'w', makeCursor(12, 2), makeCursor(11, 2));
+testMotion('w_multiple_newlines_with_space', 'w', makeCursor(14, 0), makeCursor(12, 51));
+testMotion('w_repeat', ['2', 'w'], word2.start);
+testMotion('w_wrap', ['w'], word3.start, word2.start);
+testMotion('w_endOfDocument', 'w', endOfDocument, endOfDocument);
+testMotion('w_start_to_end', ['1000', 'w'], endOfDocument, makeCursor(0, 0));
+testMotion('W', 'W', bigWord1.start);
+testMotion('W_repeat', ['2', 'W'], bigWord3.start, bigWord1.start);
+testMotion('e', 'e', word1.end);
+testMotion('e_repeat', ['2', 'e'], word2.end);
+testMotion('e_wrap', 'e', word3.end, word2.end);
+testMotion('e_endOfDocument', 'e', endOfDocument, endOfDocument);
+testMotion('e_start_to_end', ['1000', 'e'], endOfDocument, makeCursor(0, 0));
+testMotion('b', 'b', word3.start, word3.end);
+testMotion('b_repeat', ['2', 'b'], word2.start, word3.end);
+testMotion('b_wrap', 'b', word2.start, word3.start);
+testMotion('b_startOfDocument', 'b', makeCursor(0, 0), makeCursor(0, 0));
+testMotion('b_end_to_start', ['1000', 'b'], makeCursor(0, 0), endOfDocument);
+testMotion('ge', ['g', 'e'], word2.end, word3.end);
+testMotion('ge_repeat', ['2', 'g', 'e'], word1.end, word3.start);
+testMotion('ge_wrap', ['g', 'e'], word2.end, word3.start);
+testMotion('ge_startOfDocument', ['g', 'e'], makeCursor(0, 0),
+ makeCursor(0, 0));
+testMotion('ge_end_to_start', ['1000', 'g', 'e'], makeCursor(0, 0), endOfDocument);
+testMotion('gg', ['g', 'g'], makeCursor(lines[0].line, lines[0].textStart),
+ makeCursor(3, 1));
+testMotion('gg_repeat', ['3', 'g', 'g'],
+ makeCursor(lines[2].line, lines[2].textStart));
+testMotion('G', 'G',
+ makeCursor(lines[lines.length - 1].line, lines[lines.length - 1].textStart),
+ makeCursor(3, 1));
+testMotion('G_repeat', ['3', 'G'], makeCursor(lines[2].line,
+ lines[2].textStart));
+// TODO: Make the test code long enough to test Ctrl-F and Ctrl-B.
+testMotion('0', '0', makeCursor(0, 0), makeCursor(0, 8));
+testMotion('^', '^', makeCursor(0, lines[0].textStart), makeCursor(0, 8));
+testMotion('+', '+', makeCursor(1, lines[1].textStart), makeCursor(0, 8));
+testMotion('-', '-', makeCursor(0, lines[0].textStart), makeCursor(1, 4));
+testMotion('_', ['6','_'], makeCursor(5, lines[5].textStart), makeCursor(0, 8));
+testMotion('$', '$', makeCursor(0, lines[0].length - 1), makeCursor(0, 1));
+testMotion('$_repeat', ['2', '$'], makeCursor(1, lines[1].length - 1),
+ makeCursor(0, 3));
+testMotion('f', ['f', 'p'], pChars[0], makeCursor(charLine.line, 0));
+testMotion('f_repeat', ['2', 'f', 'p'], pChars[2], pChars[0]);
+testMotion('f_num', ['f', '2'], numChars[2], makeCursor(charLine.line, 0));
+testMotion('t', ['t','p'], offsetCursor(pChars[0], 0, -1),
+ makeCursor(charLine.line, 0));
+testMotion('t_repeat', ['2', 't', 'p'], offsetCursor(pChars[2], 0, -1),
+ pChars[0]);
+testMotion('F', ['F', 'p'], pChars[0], pChars[1]);
+testMotion('F_repeat', ['2', 'F', 'p'], pChars[0], pChars[2]);
+testMotion('T', ['T', 'p'], offsetCursor(pChars[0], 0, 1), pChars[1]);
+testMotion('T_repeat', ['2', 'T', 'p'], offsetCursor(pChars[0], 0, 1), pChars[2]);
+testMotion('%_parens', ['%'], parens1.end, parens1.start);
+testMotion('%_squares', ['%'], squares1.end, squares1.start);
+testMotion('%_braces', ['%'], curlys1.end, curlys1.start);
+testMotion('%_seek_outside', ['%'], seekOutside.end, seekOutside.start);
+testMotion('%_seek_inside', ['%'], seekInside.end, seekInside.start);
+testVim('%_seek_skip', function(cm, vim, helpers) {
+ cm.setCursor(0,0);
+ helpers.doKeys(['%']);
+ helpers.assertCursorAt(0,9);
+}, {value:'01234"("()'});
+testVim('%_skip_string', function(cm, vim, helpers) {
+ cm.setCursor(0,0);
+ helpers.doKeys(['%']);
+ helpers.assertCursorAt(0,4);
+ cm.setCursor(0,2);
+ helpers.doKeys(['%']);
+ helpers.assertCursorAt(0,0);
+}, {value:'(")")'});
+testVim('%_skip_comment', function(cm, vim, helpers) {
+ cm.setCursor(0,0);
+ helpers.doKeys(['%']);
+ helpers.assertCursorAt(0,6);
+ cm.setCursor(0,3);
+ helpers.doKeys(['%']);
+ helpers.assertCursorAt(0,0);
+}, {value:'(/*)*/)'});
+// Make sure that moving down after going to the end of a line always leaves you
+// at the end of a line, but preserves the offset in other cases
+testVim('Changing lines after Eol operation', function(cm, vim, helpers) {
+ cm.setCursor(0,0);
+ helpers.doKeys(['$']);
+ helpers.doKeys(['j']);
+ // After moving to Eol and then down, we should be at Eol of line 2
+ helpers.assertCursorAt(new Pos(1, lines[1].length - 1));
+ helpers.doKeys(['j']);
+ // After moving down, we should be at Eol of line 3
+ helpers.assertCursorAt(new Pos(2, lines[2].length - 1));
+ helpers.doKeys(['h']);
+ helpers.doKeys(['j']);
+ // After moving back one space and then down, since line 4 is shorter than line 2, we should
+ // be at Eol of line 2 - 1
+ helpers.assertCursorAt(new Pos(3, lines[3].length - 1));
+ helpers.doKeys(['j']);
+ helpers.doKeys(['j']);
+ // After moving down again, since line 3 has enough characters, we should be back to the
+ // same place we were at on line 1
+ helpers.assertCursorAt(new Pos(5, lines[2].length - 2));
+});
+//making sure gj and gk recover from clipping
+testVim('gj_gk_clipping', function(cm,vim,helpers){
+ cm.setCursor(0, 1);
+ helpers.doKeys('g','j','g','j');
+ helpers.assertCursorAt(2, 1);
+ helpers.doKeys('g','k','g','k');
+ helpers.assertCursorAt(0, 1);
+},{value: 'line 1\n\nline 2'});
+//testing a mix of j/k and gj/gk
+testVim('j_k_and_gj_gk', function(cm,vim,helpers){
+ cm.setSize(120);
+ cm.setCursor(0, 0);
+ //go to the last character on the first line
+ helpers.doKeys('$');
+ //move up/down on the column within the wrapped line
+ //side-effect: cursor is not locked to eol anymore
+ helpers.doKeys('g','k');
+ var cur=cm.getCursor();
+ eq(cur.line,0);
+ is((cur.ch<176),'gk didn\'t move cursor back (1)');
+ helpers.doKeys('g','j');
+ helpers.assertCursorAt(0, 176);
+ //should move to character 177 on line 2 (j/k preserve character index within line)
+ helpers.doKeys('j');
+ //due to different line wrapping, the cursor can be on a different screen-x now
+ //gj and gk preserve screen-x on movement, much like moveV
+ helpers.doKeys('3','g','k');
+ cur=cm.getCursor();
+ eq(cur.line,1);
+ is((cur.ch<176),'gk didn\'t move cursor back (2)');
+ helpers.doKeys('g','j','2','g','j');
+ //should return to the same character-index
+ helpers.doKeys('k');
+ helpers.assertCursorAt(0, 176);
+},{ lineWrapping:true, value: 'This line is intentially long to test movement of gj and gk over wrapped lines. I will start on the end of this line, then make a step up and back to set the origin for j and k.\nThis line is supposed to be even longer than the previous. I will jump here and make another wiggle with gj and gk, before I jump back to the line above. Both wiggles should not change my cursor\'s target character but both j/k and gj/gk change each other\'s reference position.'});
+testVim('gj_gk', function(cm, vim, helpers) {
+ if (phantom) return;
+ cm.setSize(120);
+ // Test top of document edge case.
+ cm.setCursor(0, 4);
+ helpers.doKeys('g', 'j');
+ helpers.doKeys('10', 'g', 'k');
+ helpers.assertCursorAt(0, 4);
+
+ // Test moving down preserves column position.
+ helpers.doKeys('g', 'j');
+ var pos1 = cm.getCursor();
+ var expectedPos2 = new Pos(0, (pos1.ch - 4) * 2 + 4);
+ helpers.doKeys('g', 'j');
+ helpers.assertCursorAt(expectedPos2);
+
+ // Move to the last character
+ cm.setCursor(0, 0);
+ // Move left to reset HSPos
+ helpers.doKeys('h');
+ // Test bottom of document edge case.
+ helpers.doKeys('100', 'g', 'j');
+ var endingPos = cm.getCursor();
+ is(endingPos != 0, 'gj should not be on wrapped line 0');
+ var topLeftCharCoords = cm.charCoords(makeCursor(0, 0));
+ var endingCharCoords = cm.charCoords(endingPos);
+ is(topLeftCharCoords.left == endingCharCoords.left, 'gj should end up on column 0');
+},{ lineNumbers: false, lineWrapping:true, value: 'Thislineisintentionallylongtotestmovementofgjandgkoverwrappedlines.' });
+testVim('}', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('}');
+ helpers.assertCursorAt(1, 0);
+ cm.setCursor(0, 0);
+ helpers.doKeys('2', '}');
+ helpers.assertCursorAt(4, 0);
+ cm.setCursor(0, 0);
+ helpers.doKeys('6', '}');
+ helpers.assertCursorAt(5, 0);
+}, { value: 'a\n\nb\nc\n\nd' });
+testVim('{', function(cm, vim, helpers) {
+ cm.setCursor(5, 0);
+ helpers.doKeys('{');
+ helpers.assertCursorAt(4, 0);
+ cm.setCursor(5, 0);
+ helpers.doKeys('2', '{');
+ helpers.assertCursorAt(1, 0);
+ cm.setCursor(5, 0);
+ helpers.doKeys('6', '{');
+ helpers.assertCursorAt(0, 0);
+}, { value: 'a\n\nb\nc\n\nd' });
+testVim('(', function(cm, vim, helpers) {
+ cm.setCursor(6, 23);
+ helpers.doKeys('(');
+ helpers.assertCursorAt(6, 14);
+ helpers.doKeys('2', '(');
+ helpers.assertCursorAt(5, 0);
+ helpers.doKeys('(');
+ helpers.assertCursorAt(4, 0);
+ helpers.doKeys('(');
+ helpers.assertCursorAt(3, 0);
+ helpers.doKeys('(');
+ helpers.assertCursorAt(2, 0);
+ helpers.doKeys('(');
+ helpers.assertCursorAt(0, 0);
+ helpers.doKeys('(');
+ helpers.assertCursorAt(0, 0);
+}, { value: 'sentence1.\n\n\nsentence2\n\nsentence3. sentence4\n sentence5? sentence6!' });
+testVim(')', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('2', ')');
+ helpers.assertCursorAt(3, 0);
+ helpers.doKeys(')');
+ helpers.assertCursorAt(4, 0);
+ helpers.doKeys(')');
+ helpers.assertCursorAt(5, 0);
+ helpers.doKeys(')');
+ helpers.assertCursorAt(5, 11);
+ helpers.doKeys(')');
+ helpers.assertCursorAt(6, 14);
+ helpers.doKeys(')');
+ helpers.assertCursorAt(6, 23);
+ helpers.doKeys(')');
+ helpers.assertCursorAt(6, 23);
+}, { value: 'sentence1.\n\n\nsentence2\n\nsentence3. sentence4\n sentence5? sentence6!' });
+testVim('paragraph_motions', function(cm, vim, helpers) {
+ cm.setCursor(10, 0);
+ helpers.doKeys('{');
+ helpers.assertCursorAt(4, 0);
+ helpers.doKeys('{');
+ helpers.assertCursorAt(0, 0);
+ helpers.doKeys('2', '}');
+ helpers.assertCursorAt(7, 0);
+ helpers.doKeys('2', '}');
+ helpers.assertCursorAt(16, 0);
+
+ cm.setCursor(9, 0);
+ helpers.doKeys('}');
+ helpers.assertCursorAt(14, 0);
+
+ cm.setCursor(6, 0);
+ helpers.doKeys('}');
+ helpers.assertCursorAt(7, 0);
+
+ // ip inside empty space
+ cm.setCursor(10, 0);
+ helpers.doKeys('v', 'i', 'p');
+ eqCursorPos(Pos(7, 0), cm.getCursor('anchor'));
+ eqCursorPos(Pos(12, 0), cm.getCursor('head'));
+ helpers.doKeys('i', 'p');
+ eqCursorPos(Pos(7, 0), cm.getCursor('anchor'));
+ eqCursorPos(Pos(13, 1), cm.getCursor('head'));
+ helpers.doKeys('2', 'i', 'p');
+ eqCursorPos(Pos(7, 0), cm.getCursor('anchor'));
+ eqCursorPos(Pos(16, 1), cm.getCursor('head'));
+
+ // should switch to visualLine mode
+ cm.setCursor(14, 0);
+ helpers.doKeys('<Esc>', 'v', 'i', 'p');
+ helpers.assertCursorAt(14, 0);
+
+ cm.setCursor(14, 0);
+ helpers.doKeys('<Esc>', 'V', 'i', 'p');
+ eqCursorPos(Pos(16, 1), cm.getCursor('head'));
+
+ // ap inside empty space
+ cm.setCursor(10, 0);
+ helpers.doKeys('<Esc>', 'v', 'a', 'p');
+ eqCursorPos(Pos(7, 0), cm.getCursor('anchor'));
+ eqCursorPos(Pos(13, 1), cm.getCursor('head'));
+ helpers.doKeys('a', 'p');
+ eqCursorPos(Pos(7, 0), cm.getCursor('anchor'));
+ eqCursorPos(Pos(16, 1), cm.getCursor('head'));
+
+ cm.setCursor(13, 0);
+ helpers.doKeys('v', 'a', 'p');
+ eqCursorPos(Pos(13, 0), cm.getCursor('anchor'));
+ eqCursorPos(Pos(14, 0), cm.getCursor('head'));
+
+ cm.setCursor(16, 0);
+ helpers.doKeys('v', 'a', 'p');
+ eqCursorPos(Pos(14, 0), cm.getCursor('anchor'));
+ eqCursorPos(Pos(16, 1), cm.getCursor('head'));
+
+ cm.setCursor(0, 0);
+ helpers.doKeys('v', 'a', 'p');
+ eqCursorPos(Pos(0, 0), cm.getCursor('anchor'));
+ eqCursorPos(Pos(4, 0), cm.getCursor('head'));
+
+ cm.setCursor(0, 0);
+ helpers.doKeys('d', 'i', 'p');
+ var register = helpers.getRegisterController().getRegister();
+ eq('a\na\n', register.toString());
+ is(register.linewise);
+ helpers.doKeys('3', 'j', 'p');
+ helpers.doKeys('y', 'i', 'p');
+ is(register.linewise);
+ eq('b\na\na\nc\n', register.toString());
+}, { value: 'a\na\n\n\n\nb\nc\n\n\n\n\n\n\nd\n\ne\nf' });
+
+// Operator tests
+testVim('dl', function(cm, vim, helpers) {
+ var curStart = makeCursor(0, 0);
+ cm.setCursor(curStart);
+ helpers.doKeys('d', 'l');
+ eq('word1 ', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq(' ', register.toString());
+ is(!register.linewise);
+ eqCursorPos(curStart, cm.getCursor());
+}, { value: ' word1 ' });
+testVim('dl_eol', function(cm, vim, helpers) {
+ cm.setCursor(0, 6);
+ helpers.doKeys('d', 'l');
+ eq(' word1', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq(' ', register.toString());
+ is(!register.linewise);
+ helpers.assertCursorAt(0, 5);
+}, { value: ' word1 ' });
+testVim('dl_repeat', function(cm, vim, helpers) {
+ var curStart = makeCursor(0, 0);
+ cm.setCursor(curStart);
+ helpers.doKeys('2', 'd', 'l');
+ eq('ord1 ', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq(' w', register.toString());
+ is(!register.linewise);
+ eqCursorPos(curStart, cm.getCursor());
+}, { value: ' word1 ' });
+testVim('dh', function(cm, vim, helpers) {
+ var curStart = makeCursor(0, 3);
+ cm.setCursor(curStart);
+ helpers.doKeys('d', 'h');
+ eq(' wrd1 ', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq('o', register.toString());
+ is(!register.linewise);
+ eqCursorPos(offsetCursor(curStart, 0 , -1), cm.getCursor());
+}, { value: ' word1 ' });
+testVim('dj', function(cm, vim, helpers) {
+ var curStart = makeCursor(0, 3);
+ cm.setCursor(curStart);
+ helpers.doKeys('d', 'j');
+ eq(' word3', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq(' word1\nword2\n', register.toString());
+ is(register.linewise);
+ helpers.assertCursorAt(0, 1);
+}, { value: ' word1\nword2\n word3' });
+testVim('dj_end_of_document', function(cm, vim, helpers) {
+ var curStart = makeCursor(0, 3);
+ cm.setCursor(curStart);
+ helpers.doKeys('d', 'j');
+ eq('', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq(' word1 \n', register.toString());
+ is(register.linewise);
+ helpers.assertCursorAt(0, 0);
+}, { value: ' word1 ' });
+testVim('dk', function(cm, vim, helpers) {
+ var curStart = makeCursor(1, 3);
+ cm.setCursor(curStart);
+ helpers.doKeys('d', 'k');
+ eq(' word3', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq(' word1\nword2\n', register.toString());
+ is(register.linewise);
+ helpers.assertCursorAt(0, 1);
+}, { value: ' word1\nword2\n word3' });
+testVim('dk_start_of_document', function(cm, vim, helpers) {
+ var curStart = makeCursor(0, 3);
+ cm.setCursor(curStart);
+ helpers.doKeys('d', 'k');
+ eq('', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq(' word1 \n', register.toString());
+ is(register.linewise);
+ helpers.assertCursorAt(0, 0);
+}, { value: ' word1 ' });
+testVim('dw_space', function(cm, vim, helpers) {
+ var curStart = makeCursor(0, 0);
+ cm.setCursor(curStart);
+ helpers.doKeys('d', 'w');
+ eq('word1 ', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq(' ', register.toString());
+ is(!register.linewise);
+ eqCursorPos(curStart, cm.getCursor());
+}, { value: ' word1 ' });
+testVim('dw_word', function(cm, vim, helpers) {
+ var curStart = makeCursor(0, 1);
+ cm.setCursor(curStart);
+ helpers.doKeys('d', 'w');
+ eq(' word2', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq('word1 ', register.toString());
+ is(!register.linewise);
+ eqCursorPos(curStart, cm.getCursor());
+}, { value: ' word1 word2' });
+testVim('dw_unicode_word', function(cm, vim, helpers) {
+ helpers.doKeys('d', 'w');
+ eq(cm.getValue().length, 10);
+ helpers.doKeys('d', 'w');
+ eq(cm.getValue().length, 6);
+ helpers.doKeys('d', 'w');
+ eq(cm.getValue().length, 5);
+ helpers.doKeys('d', 'e');
+ eq(cm.getValue().length, 2);
+}, { value: ' \u0562\u0561\u0580\u0587\xbbe\xb5g ' });
+testVim('dw_only_word', function(cm, vim, helpers) {
+ // Test that if there is only 1 word left, dw deletes till the end of the
+ // line.
+ cm.setCursor(0, 1);
+ helpers.doKeys('d', 'w');
+ eq(' ', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq('word1 ', register.toString());
+ is(!register.linewise);
+ helpers.assertCursorAt(0, 0);
+}, { value: ' word1 ' });
+testVim('dw_eol', function(cm, vim, helpers) {
+ // Assert that dw does not delete the newline if last word to delete is at end
+ // of line.
+ cm.setCursor(0, 1);
+ helpers.doKeys('d', 'w');
+ eq(' \nword2', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq('word1', register.toString());
+ is(!register.linewise);
+ helpers.assertCursorAt(0, 0);
+}, { value: ' word1\nword2' });
+testVim('dw_eol_with_multiple_newlines', function(cm, vim, helpers) {
+ // Assert that dw does not delete the newline if last word to delete is at end
+ // of line and it is followed by multiple newlines.
+ cm.setCursor(0, 1);
+ helpers.doKeys('d', 'w');
+ eq(' \n\nword2', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq('word1', register.toString());
+ is(!register.linewise);
+ helpers.assertCursorAt(0, 0);
+}, { value: ' word1\n\nword2' });
+testVim('dw_empty_line_followed_by_whitespace', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('d', 'w');
+ eq(' \nword', cm.getValue());
+}, { value: '\n \nword' });
+testVim('dw_empty_line_followed_by_word', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('d', 'w');
+ eq('word', cm.getValue());
+}, { value: '\nword' });
+testVim('dw_empty_line_followed_by_empty_line', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('d', 'w');
+ eq('\n', cm.getValue());
+}, { value: '\n\n' });
+testVim('dw_whitespace_followed_by_whitespace', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('d', 'w');
+ eq('\n \n', cm.getValue());
+}, { value: ' \n \n' });
+testVim('dw_whitespace_followed_by_empty_line', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('d', 'w');
+ eq('\n\n', cm.getValue());
+}, { value: ' \n\n' });
+testVim('dw_word_whitespace_word', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('d', 'w');
+ eq('\n \nword2', cm.getValue());
+}, { value: 'word1\n \nword2'})
+testVim('dw_end_of_document', function(cm, vim, helpers) {
+ cm.setCursor(1, 2);
+ helpers.doKeys('d', 'w');
+ eq('\nab', cm.getValue());
+}, { value: '\nabc' });
+testVim('dw_repeat', function(cm, vim, helpers) {
+ // Assert that dw does delete newline if it should go to the next line, and
+ // that repeat works properly.
+ cm.setCursor(0, 1);
+ helpers.doKeys('d', '2', 'w');
+ eq(' ', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq('word1\nword2', register.toString());
+ is(!register.linewise);
+ helpers.assertCursorAt(0, 0);
+}, { value: ' word1\nword2' });
+testVim('de_word_start_and_empty_lines', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('d', 'e');
+ eq('\n\n', cm.getValue());
+}, { value: 'word\n\n' });
+testVim('de_word_end_and_empty_lines', function(cm, vim, helpers) {
+ cm.setCursor(0, 3);
+ helpers.doKeys('d', 'e');
+ eq('wor', cm.getValue());
+}, { value: 'word\n\n\n' });
+testVim('de_whitespace_and_empty_lines', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('d', 'e');
+ eq('', cm.getValue());
+}, { value: ' \n\n\n' });
+testVim('de_end_of_document', function(cm, vim, helpers) {
+ cm.setCursor(1, 2);
+ helpers.doKeys('d', 'e');
+ eq('\nab', cm.getValue());
+}, { value: '\nabc' });
+testVim('db_empty_lines', function(cm, vim, helpers) {
+ cm.setCursor(2, 0);
+ helpers.doKeys('d', 'b');
+ eq('\n\n', cm.getValue());
+}, { value: '\n\n\n' });
+testVim('db_word_start_and_empty_lines', function(cm, vim, helpers) {
+ cm.setCursor(2, 0);
+ helpers.doKeys('d', 'b');
+ eq('\nword', cm.getValue());
+}, { value: '\n\nword' });
+testVim('db_word_end_and_empty_lines', function(cm, vim, helpers) {
+ cm.setCursor(2, 3);
+ helpers.doKeys('d', 'b');
+ eq('\n\nd', cm.getValue());
+}, { value: '\n\nword' });
+testVim('db_whitespace_and_empty_lines', function(cm, vim, helpers) {
+ cm.setCursor(2, 0);
+ helpers.doKeys('d', 'b');
+ eq('', cm.getValue());
+}, { value: '\n \n' });
+testVim('db_start_of_document', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('d', 'b');
+ eq('abc\n', cm.getValue());
+}, { value: 'abc\n' });
+testVim('dge_empty_lines', function(cm, vim, helpers) {
+ cm.setCursor(1, 0);
+ helpers.doKeys('d', 'g', 'e');
+ // Note: In real VIM the result should be '', but it's not quite consistent,
+ // since 2 newlines are deleted. But in the similar case of word\n\n, only
+ // 1 newline is deleted. We'll diverge from VIM's behavior since it's much
+ // easier this way.
+ eq('\n', cm.getValue());
+}, { value: '\n\n' });
+testVim('dge_word_and_empty_lines', function(cm, vim, helpers) {
+ cm.setCursor(1, 0);
+ helpers.doKeys('d', 'g', 'e');
+ eq('wor\n', cm.getValue());
+}, { value: 'word\n\n'});
+testVim('dge_whitespace_and_empty_lines', function(cm, vim, helpers) {
+ cm.setCursor(2, 0);
+ helpers.doKeys('d', 'g', 'e');
+ eq('', cm.getValue());
+}, { value: '\n \n' });
+testVim('dge_start_of_document', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('d', 'g', 'e');
+ eq('bc\n', cm.getValue());
+}, { value: 'abc\n' });
+testVim('d_inclusive', function(cm, vim, helpers) {
+ // Assert that when inclusive is set, the character the cursor is on gets
+ // deleted too.
+ var curStart = makeCursor(0, 1);
+ cm.setCursor(curStart);
+ helpers.doKeys('d', 'e');
+ eq(' ', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq('word1', register.toString());
+ is(!register.linewise);
+ eqCursorPos(curStart, cm.getCursor());
+}, { value: ' word1 ' });
+testVim('d_reverse', function(cm, vim, helpers) {
+ // Test that deleting in reverse works.
+ cm.setCursor(1, 0);
+ helpers.doKeys('d', 'b');
+ eq(' word2 ', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq('word1\n', register.toString());
+ is(!register.linewise);
+ helpers.assertCursorAt(0, 1);
+}, { value: ' word1\nword2 ' });
+testVim('dd', function(cm, vim, helpers) {
+ cm.setCursor(0, 3);
+ var expectedBuffer = cm.getRange(new Pos(0, 0),
+ new Pos(1, 0));
+ var expectedLineCount = cm.lineCount() - 1;
+ helpers.doKeys('d', 'd');
+ eq(expectedLineCount, cm.lineCount());
+ var register = helpers.getRegisterController().getRegister();
+ eq(expectedBuffer, register.toString());
+ is(register.linewise);
+ helpers.assertCursorAt(0, lines[1].textStart);
+});
+testVim('dd_prefix_repeat', function(cm, vim, helpers) {
+ cm.setCursor(0, 3);
+ var expectedBuffer = cm.getRange(new Pos(0, 0),
+ new Pos(2, 0));
+ var expectedLineCount = cm.lineCount() - 2;
+ helpers.doKeys('2', 'd', 'd');
+ eq(expectedLineCount, cm.lineCount());
+ var register = helpers.getRegisterController().getRegister();
+ eq(expectedBuffer, register.toString());
+ is(register.linewise);
+ helpers.assertCursorAt(0, lines[2].textStart);
+});
+testVim('dd_motion_repeat', function(cm, vim, helpers) {
+ cm.setCursor(0, 3);
+ var expectedBuffer = cm.getRange(new Pos(0, 0),
+ new Pos(2, 0));
+ var expectedLineCount = cm.lineCount() - 2;
+ helpers.doKeys('d', '2', 'd');
+ eq(expectedLineCount, cm.lineCount());
+ var register = helpers.getRegisterController().getRegister();
+ eq(expectedBuffer, register.toString());
+ is(register.linewise);
+ helpers.assertCursorAt(0, lines[2].textStart);
+});
+testVim('dd_multiply_repeat', function(cm, vim, helpers) {
+ cm.setCursor(0, 3);
+ var expectedBuffer = cm.getRange(new Pos(0, 0),
+ new Pos(6, 0));
+ var expectedLineCount = cm.lineCount() - 6;
+ helpers.doKeys('2', 'd', '3', 'd');
+ eq(expectedLineCount, cm.lineCount());
+ var register = helpers.getRegisterController().getRegister();
+ eq(expectedBuffer, register.toString());
+ is(register.linewise);
+ helpers.assertCursorAt(0, lines[6].textStart);
+});
+testVim('dd_lastline', function(cm, vim, helpers) {
+ cm.setCursor(cm.lineCount(), 0);
+ var expectedLineCount = cm.lineCount() - 1;
+ helpers.doKeys('d', 'd');
+ eq(expectedLineCount, cm.lineCount());
+ helpers.assertCursorAt(cm.lineCount() - 1, 0);
+});
+testVim('dd_only_line', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ var expectedRegister = cm.getValue() + "\n";
+ helpers.doKeys('d','d');
+ eq(1, cm.lineCount());
+ eq('', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq(expectedRegister, register.toString());
+}, { value: "thisistheonlyline" });
+// Yank commands should behave the exact same as d commands, expect that nothing
+// gets deleted.
+testVim('yw_repeat', function(cm, vim, helpers) {
+ // Assert that yw does yank newline if it should go to the next line, and
+ // that repeat works properly.
+ var curStart = makeCursor(0, 1);
+ cm.setCursor(curStart);
+ helpers.doKeys('y', '2', 'w');
+ eq(' word1\nword2', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq('word1\nword2', register.toString());
+ is(!register.linewise);
+ eqCursorPos(curStart, cm.getCursor());
+}, { value: ' word1\nword2' });
+testVim('yy_multiply_repeat', function(cm, vim, helpers) {
+ var curStart = makeCursor(0, 3);
+ cm.setCursor(curStart);
+ var expectedBuffer = cm.getRange(new Pos(0, 0),
+ new Pos(6, 0));
+ var expectedLineCount = cm.lineCount();
+ helpers.doKeys('2', 'y', '3', 'y');
+ eq(expectedLineCount, cm.lineCount());
+ var register = helpers.getRegisterController().getRegister();
+ eq(expectedBuffer, register.toString());
+ is(register.linewise);
+ eqCursorPos(curStart, cm.getCursor());
+});
+testVim('2dd_blank_P', function(cm, vim, helpers) {
+ helpers.doKeys('2', 'd', 'd', 'P');
+ eq('\na\n\n', cm.getValue());
+}, { value: '\na\n\n' });
+// Change commands behave like d commands except that it also enters insert
+// mode. In addition, when the change is linewise, an additional newline is
+// inserted so that insert mode starts on that line.
+testVim('cw', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('c', '2', 'w');
+ eq(' word3', cm.getValue());
+ helpers.assertCursorAt(0, 0);
+}, { value: 'word1 word2 word3'});
+testVim('cw_repeat', function(cm, vim, helpers) {
+ // Assert that cw does delete newline if it should go to the next line, and
+ // that repeat works properly.
+ var curStart = makeCursor(0, 1);
+ cm.setCursor(curStart);
+ helpers.doKeys('c', '2', 'w');
+ eq(' ', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq('word1\nword2', register.toString());
+ is(!register.linewise);
+ eqCursorPos(curStart, cm.getCursor());
+ eq('vim-insert', cm.getOption('keyMap'));
+}, { value: ' word1\nword2' });
+testVim('cc_multiply_repeat', function(cm, vim, helpers) {
+ cm.setCursor(0, 3);
+ var expectedBuffer = cm.getRange(new Pos(0, 0),
+ new Pos(6, 0));
+ var expectedLineCount = cm.lineCount() - 5;
+ helpers.doKeys('2', 'c', '3', 'c');
+ eq(expectedLineCount, cm.lineCount());
+ var register = helpers.getRegisterController().getRegister();
+ eq(expectedBuffer, register.toString());
+ is(register.linewise);
+ eq('vim-insert', cm.getOption('keyMap'));
+});
+testVim('ct', function(cm, vim, helpers) {
+ cm.setCursor(0, 9);
+ helpers.doKeys('c', 't', 'w');
+ eq(' word1 word3', cm.getValue());
+ helpers.doKeys('<Esc>', 'c', '|');
+ eq(' word3', cm.getValue());
+ helpers.assertCursorAt(0, 0);
+ helpers.doKeys('<Esc>', '2', 'u', 'w', 'h');
+ helpers.doKeys('c', '2', 'g', 'e');
+ eq(' wordword3', cm.getValue());
+}, { value: ' word1 word2 word3'});
+testVim('cc_should_not_append_to_document', function(cm, vim, helpers) {
+ var expectedLineCount = cm.lineCount();
+ cm.setCursor(cm.lastLine(), 0);
+ helpers.doKeys('c', 'c');
+ eq(expectedLineCount, cm.lineCount());
+});
+function fillArray(val, times) {
+ var arr = [];
+ for (var i = 0; i < times; i++) {
+ arr.push(val);
+ }
+ return arr;
+}
+testVim('c_visual_block', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.doKeys('<C-v>', '2', 'j', 'l', 'l', 'l', 'c');
+ helpers.doKeys('hello');
+ eq('1hello\n5hello\nahellofg', cm.getValue());
+ helpers.doKeys('<Esc>');
+ cm.setCursor(2, 3);
+ helpers.doKeys('<C-v>', '2', 'k', 'h', 'C');
+ helpers.doKeys('world');
+ eq('1hworld\n5hworld\nahworld', cm.getValue());
+}, {value: '1234\n5678\nabcdefg'});
+testVim('c_visual_block_replay', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.doKeys('<C-v>', '2', 'j', 'l', 'c');
+ helpers.doKeys('fo');
+ eq('1fo4\n5fo8\nafodefg', cm.getValue());
+ helpers.doKeys('<Esc>');
+ cm.setCursor(0, 0);
+ helpers.doKeys('.');
+ eq('foo4\nfoo8\nfoodefg', cm.getValue());
+}, {value: '1234\n5678\nabcdefg'});
+testVim('I_visual_block_replay', function(cm, vim, helpers) {
+ cm.setCursor(0, 2);
+ helpers.doKeys('<C-v>', '2', 'j', 'l', 'I');
+ helpers.doKeys('+-')
+ eq('12+-34\n56+-78\nab+-cdefg\nxyz', cm.getValue());
+ helpers.doKeys('<Esc>');
+ // ensure that repeat location doesn't depend on last selection
+ cm.setCursor(3, 2);
+ helpers.doKeys('g', 'v')
+ eq("+-34\n+-78\n+-cd", cm.getSelection())
+ cm.setCursor(0, 3);
+ helpers.doKeys('<C-v>', '1', 'j', '2', 'l');
+ eq("-34\n-78", cm.getSelection());
+ cm.setCursor(0, 0);
+ eq("", cm.getSelection());
+ helpers.doKeys('g', 'v');
+ eq("-34\n-78", cm.getSelection());
+ cm.setCursor(1, 1);
+ helpers.doKeys('.');
+ eq('12+-34\n5+-6+-78\na+-b+-cdefg\nx+-yz', cm.getValue());
+}, {value: '1234\n5678\nabcdefg\nxyz'});
+
+testVim('d_visual_block', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.doKeys('<C-v>', '2', 'j', 'l', 'l', 'l', 'd');
+ eq('1\n5\nafg', cm.getValue());
+}, {value: '1234\n5678\nabcdefg'});
+testVim('D_visual_block', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.doKeys('<C-v>', '2', 'j', 'l', 'D');
+ eq('1\n5\na', cm.getValue());
+}, {value: '1234\n5678\nabcdefg'});
+
+testVim('s_visual_block', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.doKeys('<C-v>', '2', 'j', 'l', 'l', 'l', 's');
+ helpers.doKeys('hello{');
+ eq('1hello{\n5hello{\nahello{fg\n', cm.getValue());
+ helpers.doKeys('<Esc>');
+ cm.setCursor(2, 3);
+ helpers.doKeys('<C-v>', '1', 'k', 'h', 'S');
+ helpers.doKeys('world');
+ eq('1hello{\n world\n', cm.getValue());
+}, {value: '1234\n5678\nabcdefg\n'});
+
+// Swapcase commands edit in place and do not modify registers.
+testVim('g~w_repeat', function(cm, vim, helpers) {
+ // Assert that dw does delete newline if it should go to the next line, and
+ // that repeat works properly.
+ var curStart = makeCursor(0, 1);
+ cm.setCursor(curStart);
+ helpers.doKeys('g', '~', '2', 'w');
+ eq(' WORD1\nWORD2', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq('', register.toString());
+ is(!register.linewise);
+ eqCursorPos(curStart, cm.getCursor());
+}, { value: ' word1\nword2' });
+testVim('g~g~', function(cm, vim, helpers) {
+ var curStart = makeCursor(0, 3);
+ cm.setCursor(curStart);
+ var expectedLineCount = cm.lineCount();
+ var expectedValue = cm.getValue().toUpperCase();
+ helpers.doKeys('2', 'g', '~', '3', 'g', '~');
+ eq(expectedValue, cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq('', register.toString());
+ is(!register.linewise);
+ eqCursorPos(curStart, cm.getCursor());
+}, { value: ' word1\nword2\nword3\nword4\nword5\nword6' });
+testVim('gu_and_gU', function(cm, vim, helpers) {
+ var curStart = makeCursor(0, 7);
+ var value = cm.getValue();
+ cm.setCursor(curStart);
+ helpers.doKeys('2', 'g', 'U', 'w');
+ eq(cm.getValue(), 'wa wb xX WC wd');
+ eqCursorPos(curStart, cm.getCursor());
+ helpers.doKeys('2', 'g', 'u', 'w');
+ eq(cm.getValue(), value);
+
+ helpers.doKeys('2', 'g', 'U', 'B');
+ eq(cm.getValue(), 'wa WB Xx wc wd');
+ eqCursorPos(makeCursor(0, 3), cm.getCursor());
+
+ cm.setCursor(makeCursor(0, 4));
+ helpers.doKeys('g', 'u', 'i', 'w');
+ eq(cm.getValue(), 'wa wb Xx wc wd');
+ eqCursorPos(makeCursor(0, 3), cm.getCursor());
+
+ // TODO: support gUgU guu
+ // eqCursorPos(makeCursor(0, 0), cm.getCursor());
+
+ var register = helpers.getRegisterController().getRegister();
+ eq('', register.toString());
+ is(!register.linewise);
+}, { value: 'wa wb xx wc wd' });
+testVim('visual_block_~', function(cm, vim, helpers) {
+ cm.setCursor(1, 1);
+ helpers.doKeys('<C-v>', 'l', 'l', 'j', '~');
+ helpers.assertCursorAt(1, 1);
+ eq('hello\nwoRLd\naBCDe', cm.getValue());
+ cm.setCursor(2, 0);
+ helpers.doKeys('v', 'l', 'l', '~');
+ helpers.assertCursorAt(2, 0);
+ eq('hello\nwoRLd\nAbcDe', cm.getValue());
+},{value: 'hello\nwOrld\nabcde' });
+testVim('._swapCase_visualBlock', function(cm, vim, helpers) {
+ helpers.doKeys('<C-v>', 'j', 'j', 'l', '~');
+ cm.setCursor(0, 3);
+ helpers.doKeys('.');
+ eq('HelLO\nWorLd\nAbcdE', cm.getValue());
+},{value: 'hEllo\nwOrlD\naBcDe' });
+testVim('._delete_visualBlock', function(cm, vim, helpers) {
+ helpers.doKeys('<C-v>', 'j', 'x');
+ eq('ive\ne\nsome\nsugar', cm.getValue());
+ helpers.doKeys('.');
+ eq('ve\n\nsome\nsugar', cm.getValue());
+ helpers.doKeys('j', 'j', '.');
+ eq('ve\n\nome\nugar', cm.getValue());
+ helpers.doKeys('u', '<C-r>', '.');
+ eq('ve\n\nme\ngar', cm.getValue());
+},{value: 'give\nme\nsome\nsugar' });
+testVim('>{motion}', function(cm, vim, helpers) {
+ cm.setCursor(1, 3);
+ var expectedLineCount = cm.lineCount();
+ var expectedValue = ' word1\n word2\nword3 ';
+ helpers.doKeys('>', 'k');
+ eq(expectedValue, cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq('', register.toString());
+ is(!register.linewise);
+ helpers.assertCursorAt(0, 3);
+}, { value: ' word1\nword2\nword3 ', indentUnit: 2 });
+testVim('>>', function(cm, vim, helpers) {
+ cm.setCursor(0, 3);
+ var expectedLineCount = cm.lineCount();
+ var expectedValue = ' word1\n word2\nword3 ';
+ helpers.doKeys('2', '>', '>');
+ eq(expectedValue, cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq('', register.toString());
+ is(!register.linewise);
+ helpers.assertCursorAt(0, 3);
+}, { value: ' word1\nword2\nword3 ', indentUnit: 2 });
+testVim('<{motion}', function(cm, vim, helpers) {
+ cm.setCursor(1, 3);
+ var expectedLineCount = cm.lineCount();
+ var expectedValue = ' word1\nword2\nword3 ';
+ helpers.doKeys('<', 'k');
+ eq(expectedValue, cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq('', register.toString());
+ is(!register.linewise);
+ helpers.assertCursorAt(0, 1);
+}, { value: ' word1\n word2\nword3 ', indentUnit: 2 });
+testVim('<<', function(cm, vim, helpers) {
+ cm.setCursor(0, 3);
+ var expectedLineCount = cm.lineCount();
+ var expectedValue = ' word1\nword2\nword3 ';
+ helpers.doKeys('2', '<', '<');
+ eq(expectedValue, cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq('', register.toString());
+ is(!register.linewise);
+ helpers.assertCursorAt(0, 1);
+}, { value: ' word1\n word2\nword3 ', indentUnit: 2 });
+testVim('=', function(cm, vim, helpers) {
+ cm.setCursor(0, 3);
+ helpers.doKeys('<C-v>', 'j', 'j');
+ var expectedValue = 'word1\nword2\nword3';
+ helpers.doKeys('=');
+ eq(expectedValue, cm.getValue());
+}, { value: ' word1\n word2\n word3', indentUnit: 2 });
+
+// Edit tests
+function testEdit(name, before, pos, edit, after) {
+ return testVim(name, function(cm, vim, helpers) {
+ var ch = before.search(pos)
+ var line = before.substring(0, ch).split('\n').length - 1;
+ if (line) {
+ ch = before.substring(0, ch).split('\n').pop().length;
+ }
+ cm.setCursor(line, ch);
+ helpers.doKeys.apply(this, edit.split(''));
+ eq(after, cm.getValue());
+ }, {value: before});
+}
+
+// These Delete tests effectively cover word-wise Change, Visual & Yank.
+// Tabs are used as differentiated whitespace to catch edge cases.
+// Normal word:
+testEdit('diw_mid_spc', 'foo \tbAr\t baz', /A/, 'diw', 'foo \t\t baz');
+testEdit('daw_mid_spc', 'foo \tbAr\t baz', /A/, 'daw', 'foo \tbaz');
+testEdit('diw_mid_punct', 'foo \tbAr.\t baz', /A/, 'diw', 'foo \t.\t baz');
+testEdit('daw_mid_punct', 'foo \tbAr.\t baz', /A/, 'daw', 'foo.\t baz');
+testEdit('diw_mid_punct2', 'foo \t,bAr.\t baz', /A/, 'diw', 'foo \t,.\t baz');
+testEdit('daw_mid_punct2', 'foo \t,bAr.\t baz', /A/, 'daw', 'foo \t,.\t baz');
+testEdit('diw_start_spc', 'bAr \tbaz', /A/, 'diw', ' \tbaz');
+testEdit('daw_start_spc', 'bAr \tbaz', /A/, 'daw', 'baz');
+testEdit('diw_start_punct', 'bAr. \tbaz', /A/, 'diw', '. \tbaz');
+testEdit('daw_start_punct', 'bAr. \tbaz', /A/, 'daw', '. \tbaz');
+testEdit('diw_end_spc', 'foo \tbAr', /A/, 'diw', 'foo \t');
+testEdit('daw_end_spc', 'foo \tbAr', /A/, 'daw', 'foo');
+testEdit('diw_end_punct', 'foo \tbAr.', /A/, 'diw', 'foo \t.');
+testEdit('daw_end_punct', 'foo \tbAr.', /A/, 'daw', 'foo.');
+// Big word:
+testEdit('diW_mid_spc', 'foo \tbAr\t baz', /A/, 'diW', 'foo \t\t baz');
+testEdit('daW_mid_spc', 'foo \tbAr\t baz', /A/, 'daW', 'foo \tbaz');
+testEdit('diW_mid_punct', 'foo \tbAr.\t baz', /A/, 'diW', 'foo \t\t baz');
+testEdit('daW_mid_punct', 'foo \tbAr.\t baz', /A/, 'daW', 'foo \tbaz');
+testEdit('diW_mid_punct2', 'foo \t,bAr.\t baz', /A/, 'diW', 'foo \t\t baz');
+testEdit('daW_mid_punct2', 'foo \t,bAr.\t baz', /A/, 'daW', 'foo \tbaz');
+testEdit('diW_start_spc', 'bAr\t baz', /A/, 'diW', '\t baz');
+testEdit('daW_start_spc', 'bAr\t baz', /A/, 'daW', 'baz');
+testEdit('diW_start_punct', 'bAr.\t baz', /A/, 'diW', '\t baz');
+testEdit('daW_start_punct', 'bAr.\t baz', /A/, 'daW', 'baz');
+testEdit('diW_end_spc', 'foo \tbAr', /A/, 'diW', 'foo \t');
+testEdit('daW_end_spc', 'foo \tbAr', /A/, 'daW', 'foo');
+testEdit('diW_end_punct', 'foo \tbAr.', /A/, 'diW', 'foo \t');
+testEdit('daW_end_punct', 'foo \tbAr.', /A/, 'daW', 'foo');
+// Deleting text objects
+// Open and close on same line
+testEdit('di(_open_spc', 'foo (bAr) baz', /\(/, 'di(', 'foo () baz');
+testEdit('di)_open_spc', 'foo (bAr) baz', /\(/, 'di)', 'foo () baz');
+testEdit('dib_open_spc', 'foo (bAr) baz', /\(/, 'dib', 'foo () baz');
+testEdit('da(_open_spc', 'foo (bAr) baz', /\(/, 'da(', 'foo baz');
+testEdit('da)_open_spc', 'foo (bAr) baz', /\(/, 'da)', 'foo baz');
+
+testEdit('di(_middle_spc', 'foo (bAr) baz', /A/, 'di(', 'foo () baz');
+testEdit('di)_middle_spc', 'foo (bAr) baz', /A/, 'di)', 'foo () baz');
+testEdit('da(_middle_spc', 'foo (bAr) baz', /A/, 'da(', 'foo baz');
+testEdit('da)_middle_spc', 'foo (bAr) baz', /A/, 'da)', 'foo baz');
+
+testEdit('di(_close_spc', 'foo (bAr) baz', /\)/, 'di(', 'foo () baz');
+testEdit('di)_close_spc', 'foo (bAr) baz', /\)/, 'di)', 'foo () baz');
+testEdit('da(_close_spc', 'foo (bAr) baz', /\)/, 'da(', 'foo baz');
+testEdit('da)_close_spc', 'foo (bAr) baz', /\)/, 'da)', 'foo baz');
+
+testEdit('di`', 'foo `bAr` baz', /`/, 'di`', 'foo `` baz');
+testEdit('di>', 'foo <bAr> baz', /</, 'di>', 'foo <> baz');
+testEdit('da<', 'foo <bAr> baz', /</, 'da<', 'foo baz');
+
+// delete around and inner b.
+testEdit('dab_on_(_should_delete_around_()block', 'o( in(abc) )', /\(a/, 'dab', 'o( in )');
+
+// delete around and inner B.
+testEdit('daB_on_{_should_delete_around_{}block', 'o{ in{abc} }', /{a/, 'daB', 'o{ in }');
+testEdit('diB_on_{_should_delete_inner_{}block', 'o{ in{abc} }', /{a/, 'diB', 'o{ in{} }');
+
+testEdit('da{_on_{_should_delete_inner_block', 'o{ in{abc} }', /{a/, 'da{', 'o{ in }');
+testEdit('di[_on_(_should_not_delete', 'foo (bAr) baz', /\(/, 'di[', 'foo (bAr) baz');
+testEdit('di[_on_)_should_not_delete', 'foo (bAr) baz', /\)/, 'di[', 'foo (bAr) baz');
+testEdit('da[_on_(_should_not_delete', 'foo (bAr) baz', /\(/, 'da[', 'foo (bAr) baz');
+testEdit('da[_on_)_should_not_delete', 'foo (bAr) baz', /\)/, 'da[', 'foo (bAr) baz');
+testMotion('di(_outside_should_stay', ['d', 'i', '('], new Pos(0, 0), new Pos(0, 0));
+
+// Open and close on different lines, equally indented
+testEdit('di{_middle_spc', 'a{\n\tbar\n}b', /r/, 'di{', 'a{}b');
+testEdit('di}_middle_spc', 'a{\n\tbar\n}b', /r/, 'di}', 'a{}b');
+testEdit('da{_middle_spc', 'a{\n\tbar\n}b', /r/, 'da{', 'ab');
+testEdit('da}_middle_spc', 'a{\n\tbar\n}b', /r/, 'da}', 'ab');
+testEdit('daB_middle_spc', 'a{\n\tbar\n}b', /r/, 'daB', 'ab');
+
+// open and close on diff lines, open indented less than close
+testEdit('di{_middle_spc', 'a{\n\tbar\n\t}b', /r/, 'di{', 'a{}b');
+testEdit('di}_middle_spc', 'a{\n\tbar\n\t}b', /r/, 'di}', 'a{}b');
+testEdit('da{_middle_spc', 'a{\n\tbar\n\t}b', /r/, 'da{', 'ab');
+testEdit('da}_middle_spc', 'a{\n\tbar\n\t}b', /r/, 'da}', 'ab');
+
+// open and close on diff lines, open indented more than close
+testEdit('di[_middle_spc', 'a\t[\n\tbar\n]b', /r/, 'di[', 'a\t[]b');
+testEdit('di]_middle_spc', 'a\t[\n\tbar\n]b', /r/, 'di]', 'a\t[]b');
+testEdit('da[_middle_spc', 'a\t[\n\tbar\n]b', /r/, 'da[', 'a\tb');
+testEdit('da]_middle_spc', 'a\t[\n\tbar\n]b', /r/, 'da]', 'a\tb');
+
+// open and close on diff lines, open indented more than close
+testEdit('di<_middle_spc', 'a\t<\n\tbar\n>b', /r/, 'di<', 'a\t<>b');
+testEdit('di>_middle_spc', 'a\t<\n\tbar\n>b', /r/, 'di>', 'a\t<>b');
+testEdit('da<_middle_spc', 'a\t<\n\tbar\n>b', /r/, 'da<', 'a\tb');
+testEdit('da>_middle_spc', 'a\t<\n\tbar\n>b', /r/, 'da>', 'a\tb');
+
+function testSelection(name, before, pos, keys, sel) {
+ return testVim(name, function(cm, vim, helpers) {
+ var ch = before.search(pos)
+ var line = before.substring(0, ch).split('\n').length - 1;
+ if (line) {
+ ch = before.substring(0, ch).split('\n').pop().length;
+ }
+ cm.setCursor(line, ch);
+ helpers.doKeys.apply(this, keys.split(''));
+ eq(sel, cm.getSelection());
+ }, {value: before});
+}
+testSelection('viw_middle_spc', 'foo \tbAr\t baz', /A/, 'viw', 'bAr');
+testSelection('vaw_middle_spc', 'foo \tbAr\t baz', /A/, 'vaw', 'bAr\t ');
+testSelection('viw_middle_punct', 'foo \tbAr,\t baz', /A/, 'viw', 'bAr');
+testSelection('vaW_middle_punct', 'foo \tbAr,\t baz', /A/, 'vaW', 'bAr,\t ');
+testSelection('viw_start_spc', 'foo \tbAr\t baz', /b/, 'viw', 'bAr');
+testSelection('viw_end_spc', 'foo \tbAr\t baz', /r/, 'viw', 'bAr');
+testSelection('viw_eol', 'foo \tbAr', /r/, 'viw', 'bAr');
+testSelection('vi{_middle_spc', 'a{\n\tbar\n\t}b', /r/, 'vi{', '\n\tbar\n\t');
+testSelection('va{_middle_spc', 'a{\n\tbar\n\t}b', /r/, 'va{', '{\n\tbar\n\t}');
+
+testVim('mouse_select', function(cm, vim, helpers) {
+ cm.setSelection(Pos(0, 2), Pos(0, 4), {origin: '*mouse'});
+ is(cm.state.vim.visualMode);
+ is(!cm.state.vim.visualLine);
+ is(!cm.state.vim.visualBlock);
+ helpers.doKeys('<Esc>');
+ is(!cm.somethingSelected());
+ helpers.doKeys('g', 'v');
+ eq('cd', cm.getSelection());
+}, {value: 'abcdef'});
+
+// Operator-motion tests
+testVim('D', function(cm, vim, helpers) {
+ cm.setCursor(0, 3);
+ helpers.doKeys('D');
+ eq(' wo\nword2\n word3', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq('rd1', register.toString());
+ is(!register.linewise);
+ helpers.assertCursorAt(0, 2);
+}, { value: ' word1\nword2\n word3' });
+testVim('C', function(cm, vim, helpers) {
+ var curStart = makeCursor(0, 3);
+ cm.setCursor(curStart);
+ helpers.doKeys('C');
+ eq(' wo\nword2\n word3', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq('rd1', register.toString());
+ is(!register.linewise);
+ eqCursorPos(curStart, cm.getCursor());
+ eq('vim-insert', cm.getOption('keyMap'));
+}, { value: ' word1\nword2\n word3' });
+testVim('Y', function(cm, vim, helpers) {
+ var curStart = makeCursor(0, 3);
+ cm.setCursor(curStart);
+ helpers.doKeys('Y');
+ eq(' word1\nword2\n word3', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq(' word1\n', register.toString());
+ is(register.linewise);
+ helpers.assertCursorAt(0, 3);
+}, { value: ' word1\nword2\n word3' });
+testVim('Yy_blockwise', function(cm, vim, helpers) {
+ helpers.doKeys('<C-v>', 'j', '2', 'l', 'Y');
+ helpers.doKeys('G', 'p', 'g', 'g');
+ helpers.doKeys('<C-v>', 'j', '2', 'l', 'y');
+ helpers.assertCursorAt(0, 0);
+ helpers.doKeys('$', 'p');
+ eq('123456123\n123456123\n123456\n123456', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq('123\n123', register.toString());
+ is(register.blockwise);
+ helpers.assertCursorAt(0, 6);
+ helpers.doKeys('$', 'j', 'p');
+ helpers.doKeys('$', 'j', 'P');
+ eq("123456123\n123456123123\n123456 121233\n123456 123", cm.getValue());
+}, { value: '123456\n123456\n' });
+testVim('~', function(cm, vim, helpers) {
+ helpers.doKeys('3', '~');
+ eq('ABCdefg', cm.getValue());
+ helpers.assertCursorAt(0, 3);
+}, { value: 'abcdefg' });
+
+// Action tests
+testVim('ctrl-a', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('<C-a>');
+ eq('-9', cm.getValue());
+ helpers.assertCursorAt(0, 1);
+ helpers.doKeys('2','<C-a>');
+ eq('-7', cm.getValue());
+}, {value: '-10'});
+testVim('ctrl-x', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('<C-x>');
+ eq('-1', cm.getValue());
+ helpers.assertCursorAt(0, 1);
+ helpers.doKeys('2','<C-x>');
+ eq('-3', cm.getValue());
+}, {value: '0'});
+testVim('<C-x>/<C-a> search forward', function(cm, vim, helpers) {
+ forEach(['<C-x>', '<C-a>'], function(key) {
+ cm.setCursor(0, 0);
+ helpers.doKeys(key);
+ helpers.assertCursorAt(0, 5);
+ helpers.doKeys('l');
+ helpers.doKeys(key);
+ helpers.assertCursorAt(0, 10);
+ cm.setCursor(0, 11);
+ helpers.doKeys(key);
+ helpers.assertCursorAt(0, 11);
+ });
+}, {value: '__jmp1 jmp2 jmp'});
+testVim('insert_ctrl_w', function(cm, vim, helpers) {
+ var curStart = makeCursor(0, 10);
+ cm.setCursor(curStart);
+ helpers.doKeys('a');
+ helpers.doKeys('<C-w>');
+ eq('word1/', cm.getValue());
+ var register = helpers.getRegisterController().getRegister();
+ eq('word2', register.toString());
+ is(!register.linewise);
+ var curEnd = makeCursor(0, 6);
+ eqCursorPos(curEnd, cm.getCursor());
+ eq('vim-insert', cm.getOption('keyMap'));
+}, { value: 'word1/word2' });
+testVim('normal_ctrl_w', function(cm, vim, helpers) {
+ var curStart = makeCursor(0, 3);
+ cm.setCursor(curStart);
+ helpers.doKeys('<C-w>');
+ eq('word', cm.getValue());
+ var curEnd = makeCursor(0, 3);
+ helpers.assertCursorAt(0,3);
+ eqCursorPos(curEnd, cm.getCursor());
+ eq('vim', cm.getOption('keyMap'));
+}, {value: 'word'});
+testVim('a', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.doKeys('a');
+ helpers.assertCursorAt(0, 2);
+ eq('vim-insert', cm.getOption('keyMap'));
+});
+testVim('a_eol', function(cm, vim, helpers) {
+ cm.setCursor(0, lines[0].length - 1);
+ helpers.doKeys('a');
+ helpers.assertCursorAt(0, lines[0].length);
+ eq('vim-insert', cm.getOption('keyMap'));
+});
+testVim('A_endOfSelectedArea', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('v', 'j', 'l');
+ helpers.doKeys('A');
+ helpers.assertCursorAt(1, 2);
+ eq('vim-insert', cm.getOption('keyMap'));
+}, {value: 'foo\nbar'});
+testVim('i', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.doKeys('i');
+ helpers.assertCursorAt(0, 1);
+ eq('vim-insert', cm.getOption('keyMap'));
+});
+testVim('i_repeat', function(cm, vim, helpers) {
+ helpers.doKeys('3', 'i');
+ helpers.doKeys('test')
+ helpers.doKeys('<Esc>');
+ eq('testtesttest', cm.getValue());
+ helpers.assertCursorAt(0, 11);
+}, { value: '' });
+testVim('i_repeat_delete', function(cm, vim, helpers) {
+ cm.setCursor(0, 4);
+ helpers.doKeys('2', 'i');
+ helpers.doKeys('z')
+ helpers.doInsertModeKeys('Backspace', 'Backspace');
+ helpers.doKeys('<Esc>');
+ eq('abe', cm.getValue());
+ helpers.assertCursorAt(0, 1);
+}, { value: 'abcde' });
+testVim('insert', function(cm, vim, helpers) {
+ helpers.doKeys('i');
+ eq('vim-insert', cm.getOption('keyMap'));
+ eq(false, cm.state.overwrite);
+ helpers.doKeys('<Ins>');
+ eq('vim-replace', cm.getOption('keyMap'));
+ eq(true, cm.state.overwrite);
+ helpers.doKeys('<Ins>');
+ eq('vim-insert', cm.getOption('keyMap'));
+ eq(false, cm.state.overwrite);
+});
+testVim('i_backspace', function(cm, vim, helpers) {
+ cm.setCursor(0, 10);
+ helpers.doKeys('i');
+ helpers.doInsertModeKeys('Backspace');
+ helpers.assertCursorAt(0, 9);
+ eq('012345678', cm.getValue());
+}, { value: '0123456789'});
+testVim('i_overwrite_backspace', function(cm, vim, helpers) {
+ cm.setCursor(0, 10);
+ helpers.doKeys('i');
+ helpers.doKeys('<Ins>');
+ helpers.doInsertModeKeys('Backspace');
+ helpers.assertCursorAt(Pos(0, 9, "after"));
+ eq('0123456789', cm.getValue());
+}, { value: '0123456789'});
+testVim('i_forward_delete', function(cm, vim, helpers) {
+ cm.setCursor(0, 3);
+ helpers.doKeys('i');
+ helpers.doInsertModeKeys('Delete');
+ helpers.assertCursorAt(0, 3);
+ eq('A124\nBCD', cm.getValue());
+ helpers.doInsertModeKeys('Delete');
+ helpers.assertCursorAt(0, 3);
+ eq('A12\nBCD', cm.getValue());
+ helpers.doInsertModeKeys('Delete');
+ helpers.assertCursorAt(0, 3);
+ eq('A12BCD', cm.getValue());
+}, { value: 'A1234\nBCD'});
+testVim('forward_delete', function(cm, vim, helpers) {
+ cm.setCursor(0, 3);
+ helpers.doInsertModeKeys('Delete');
+ helpers.assertCursorAt(0, 3);
+ eq('A124\nBCD', cm.getValue());
+ helpers.doInsertModeKeys('Delete');
+ helpers.assertCursorAt(0, 2);
+ eq('A12\nBCD', cm.getValue());
+ helpers.doInsertModeKeys('Delete');
+ helpers.assertCursorAt(0, 1);
+ eq('A1\nBCD', cm.getValue());
+}, { value: 'A1234\nBCD'});
+testVim('A', function(cm, vim, helpers) {
+ helpers.doKeys('A');
+ helpers.assertCursorAt(0, lines[0].length);
+ eq('vim-insert', cm.getOption('keyMap'));
+});
+testVim('A_visual_block', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.doKeys('<C-v>', '2', 'j', 'l', 'l', 'A');
+ helpers.doKeys('hello');
+ eq('testhello\nmehello\npleahellose', cm.getValue());
+ helpers.doKeys('<Esc>');
+ cm.setCursor(0, 0);
+ helpers.doKeys('.');
+ // TODO this doesn't work yet
+ // eq('teshellothello\nme hello hello\nplehelloahellose', cm.getValue());
+}, {value: 'test\nme\nplease'});
+testVim('I', function(cm, vim, helpers) {
+ cm.setCursor(0, 4);
+ helpers.doKeys('I');
+ helpers.assertCursorAt(0, lines[0].textStart);
+ eq('vim-insert', cm.getOption('keyMap'));
+});
+testVim('I_repeat', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.doKeys('3', 'I');
+ helpers.doKeys('test')
+ helpers.doKeys('<Esc>');
+ eq('testtesttestblah', cm.getValue());
+ helpers.assertCursorAt(0, 11);
+}, { value: 'blah' });
+testVim('I_visual_block', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('<C-v>', '2', 'j', 'l', 'l', 'I');
+ helpers.doKeys('hello');
+ eq('hellotest\nhellome\nhelloplease', cm.getValue());
+}, {value: 'test\nme\nplease'});
+testVim('o', function(cm, vim, helpers) {
+ cm.setCursor(0, 4);
+ helpers.doKeys('o');
+ eq('word1\n\nword2', cm.getValue());
+ helpers.assertCursorAt(1, 0);
+ eq('vim-insert', cm.getOption('keyMap'));
+}, { value: 'word1\nword2' });
+testVim('o_repeat', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('3', 'o');
+ helpers.doKeys('test')
+ helpers.doKeys('<Esc>');
+ eq('\ntest\ntest\ntest', cm.getValue());
+ helpers.assertCursorAt(3, 3);
+}, { value: '' });
+testVim('O', function(cm, vim, helpers) {
+ cm.setCursor(0, 4);
+ helpers.doKeys('O');
+ eq('\nword1\nword2', cm.getValue());
+ helpers.assertCursorAt(0, 0);
+ eq('vim-insert', cm.getOption('keyMap'));
+}, { value: 'word1\nword2' });
+testVim('J', function(cm, vim, helpers) {
+ cm.setCursor(0, 4);
+ helpers.doKeys('J');
+ var expectedValue = 'word1 word2\nword3\n word4';
+ eq(expectedValue, cm.getValue());
+ helpers.assertCursorAt(0, expectedValue.indexOf('word2') - 1);
+}, { value: 'word1 \n word2\nword3\n word4' });
+testVim('J_repeat', function(cm, vim, helpers) {
+ cm.setCursor(0, 4);
+ helpers.doKeys('3', 'J');
+ var expectedValue = 'word1 word2 word3\n word4';
+ eq(expectedValue, cm.getValue());
+ helpers.assertCursorAt(0, expectedValue.indexOf('word3') - 1);
+}, { value: 'word1 \n word2\nword3\n word4' });
+testVim('p', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.getRegisterController().pushText('"', 'yank', 'abc\ndef', false);
+ helpers.doKeys('p');
+ eq('__abc\ndef_', cm.getValue());
+ helpers.assertCursorAt(1, 2);
+}, { value: '___' });
+testVim('p_register', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.getRegisterController().getRegister('a').setText('abc\ndef', false);
+ helpers.doKeys('"', 'a', 'p');
+ eq('__abc\ndef_', cm.getValue());
+ helpers.assertCursorAt(1, 2);
+}, { value: '___' });
+testVim('p_wrong_register', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.getRegisterController().getRegister('a').setText('abc\ndef', false);
+ helpers.doKeys('p');
+ eq('___', cm.getValue());
+ helpers.assertCursorAt(0, 1);
+}, { value: '___' });
+testVim('p_line', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.getRegisterController().pushText('"', 'yank', ' a\nd\n', true);
+ helpers.doKeys('2', 'p');
+ eq('___\n a\nd\n a\nd', cm.getValue());
+ helpers.assertCursorAt(1, 2);
+}, { value: '___' });
+testVim('p_lastline', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.getRegisterController().pushText('"', 'yank', ' a\nd', true);
+ helpers.doKeys('2', 'p');
+ eq('___\n a\nd\n a\nd', cm.getValue());
+ helpers.assertCursorAt(1, 2);
+}, { value: '___' });
+testVim(']p_first_indent_is_smaller', function(cm, vim, helpers) {
+ helpers.getRegisterController().pushText('"', 'yank', ' abc\n def\n', true);
+ helpers.doKeys(']', 'p');
+ eq(' ___\n abc\n def', cm.getValue());
+}, { value: ' ___' });
+testVim(']p_first_indent_is_larger', function(cm, vim, helpers) {
+ helpers.getRegisterController().pushText('"', 'yank', ' abc\n def\n', true);
+ helpers.doKeys(']', 'p');
+ eq(' ___\n abc\ndef', cm.getValue());
+}, { value: ' ___' });
+testVim(']p_with_tab_indents', function(cm, vim, helpers) {
+ helpers.getRegisterController().pushText('"', 'yank', '\t\tabc\n\t\t\tdef\n', true);
+ helpers.doKeys(']', 'p');
+ eq('\t___\n\tabc\n\t\tdef', cm.getValue());
+}, { value: '\t___', indentWithTabs: true});
+testVim(']p_with_spaces_translated_to_tabs', function(cm, vim, helpers) {
+ helpers.getRegisterController().pushText('"', 'yank', ' abc\n def\n', true);
+ helpers.doKeys(']', 'p');
+ eq('\t___\n\tabc\n\t\tdef', cm.getValue());
+}, { value: '\t___', indentWithTabs: true, tabSize: 2 });
+testVim('[p', function(cm, vim, helpers) {
+ helpers.getRegisterController().pushText('"', 'yank', ' abc\n def\n', true);
+ helpers.doKeys('[', 'p');
+ eq(' abc\n def\n ___', cm.getValue());
+}, { value: ' ___' });
+testVim('P', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.getRegisterController().pushText('"', 'yank', 'abc\ndef', false);
+ helpers.doKeys('P');
+ eq('_abc\ndef__', cm.getValue());
+ helpers.assertCursorAt(1, 3);
+}, { value: '___' });
+testVim('P_line', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.getRegisterController().pushText('"', 'yank', ' a\nd\n', true);
+ helpers.doKeys('2', 'P');
+ eq(' a\nd\n a\nd\n___', cm.getValue());
+ helpers.assertCursorAt(0, 2);
+}, { value: '___' });
+testVim('r', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.doKeys('3', 'r', 'u');
+ eq('wuuuet\nanother', cm.getValue(),'3r failed');
+ helpers.assertCursorAt(0, 3);
+ cm.setCursor(0, 4);
+ helpers.doKeys('v', 'j', 'h', 'r', '<Space>');
+ eq('wuuu \n her', cm.getValue(),'Replacing selection by space-characters failed');
+ cm.setValue("ox");
+ helpers.doKeys('r', '<C-c>');
+ eq('ox', cm.getValue());
+ helpers.doKeys('r', '<Del>');
+ eq('ox', cm.getValue());
+ helpers.doKeys('r', '<CR>');
+ eq('\nx', cm.getValue());
+}, { value: 'wordet\nanother' });
+testVim('r_visual_block', function(cm, vim, helpers) {
+ cm.setCursor(2, 3);
+ helpers.doKeys('<C-v>', 'k', 'k', 'h', 'h', 'r', 'l');
+ eq('1lll\n5lll\nalllefg', cm.getValue());
+ helpers.doKeys('<C-v>', 'l', 'j', 'r', '<Space>');
+ eq('1 l\n5 l\nalllefg', cm.getValue());
+ cm.setCursor(2, 0);
+ helpers.doKeys('o');
+ helpers.doKeys('\t\t')
+ helpers.doKeys('<Esc>');
+ helpers.doKeys('<C-v>', 'h', 'h', 'r', 'r');
+ eq('1 l\n5 l\nalllefg\nrrrrrrrr', cm.getValue());
+}, {value: '1234\n5678\nabcdefg'});
+testVim('R', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.doKeys('R');
+ helpers.assertCursorAt(0, 1);
+ eq('vim-replace', cm.getOption('keyMap'));
+ is(cm.state.overwrite, 'Setting overwrite state failed');
+});
+testVim('mark', function(cm, vim, helpers) {
+ cm.setCursor(2, 2);
+ helpers.doKeys('m', 't');
+ cm.setCursor(0, 0);
+ helpers.doKeys('`', 't');
+ helpers.assertCursorAt(2, 2);
+ cm.setCursor(2, 0);
+ cm.replaceRange(' h', cm.getCursor());
+ cm.setCursor(0, 0);
+ helpers.doKeys('\'', 't');
+ helpers.assertCursorAt(2, 3);
+});
+testVim('mark\'', function(cm, vim, helpers) {
+ cm.setCursor(2, 2);
+ cm.setCursor(0, 0);
+ helpers.doKeys('`', '\'');
+ helpers.assertCursorAt(2, 2);
+ cm.setCursor(2, 0);
+ cm.replaceRange(' h', cm.getCursor());
+ cm.setCursor(0, 0);
+ helpers.doKeys('\'', '\'');
+ helpers.assertCursorAt(2, 3);
+});
+testVim('mark.', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('O', 'testing', '<Esc>');
+ cm.setCursor(3, 3);
+ helpers.doKeys('\'', '.');
+ helpers.assertCursorAt(0, 0);
+ cm.setCursor(4, 4);
+ helpers.doKeys('`', '.');
+ helpers.assertCursorAt(0, 6);
+});
+testVim('jumpToMark_next', function(cm, vim, helpers) {
+ cm.setCursor(2, 2);
+ helpers.doKeys('m', 't');
+ cm.setCursor(0, 0);
+ helpers.doKeys(']', '`');
+ helpers.assertCursorAt(2, 2);
+ cm.setCursor(0, 0);
+ helpers.doKeys(']', '\'');
+ helpers.assertCursorAt(2, 0);
+});
+testVim('jumpToMark_next_repeat', function(cm, vim, helpers) {
+ cm.setCursor(2, 2);
+ helpers.doKeys('m', 'a');
+ cm.setCursor(3, 2);
+ helpers.doKeys('m', 'b');
+ cm.setCursor(4, 2);
+ helpers.doKeys('m', 'c');
+ cm.setCursor(0, 0);
+ helpers.doKeys('2', ']', '`');
+ helpers.assertCursorAt(3, 2);
+ cm.setCursor(0, 0);
+ helpers.doKeys('2', ']', '\'');
+ helpers.assertCursorAt(3, 1);
+});
+testVim('jumpToMark_next_sameline', function(cm, vim, helpers) {
+ cm.setCursor(2, 0);
+ helpers.doKeys('m', 'a');
+ cm.setCursor(2, 4);
+ helpers.doKeys('m', 'b');
+ cm.setCursor(2, 2);
+ helpers.doKeys(']', '`');
+ helpers.assertCursorAt(2, 4);
+});
+testVim('jumpToMark_next_onlyprev', function(cm, vim, helpers) {
+ cm.setCursor(2, 0);
+ helpers.doKeys('m', 'a');
+ cm.setCursor(4, 0);
+ helpers.doKeys(']', '`');
+ helpers.assertCursorAt(4, 0);
+});
+testVim('jumpToMark_next_nomark', function(cm, vim, helpers) {
+ cm.setCursor(2, 2);
+ helpers.doKeys(']', '`');
+ helpers.assertCursorAt(2, 2);
+ helpers.doKeys(']', '\'');
+ helpers.assertCursorAt(2, 0);
+});
+testVim('jumpToMark_next_linewise_over', function(cm, vim, helpers) {
+ cm.setCursor(2, 2);
+ helpers.doKeys('m', 'a');
+ cm.setCursor(3, 4);
+ helpers.doKeys('m', 'b');
+ cm.setCursor(2, 1);
+ helpers.doKeys(']', '\'');
+ helpers.assertCursorAt(3, 1);
+});
+testVim('jumpToMark_next_action', function(cm, vim, helpers) {
+ cm.setCursor(2, 2);
+ helpers.doKeys('m', 't');
+ cm.setCursor(0, 0);
+ helpers.doKeys('d', ']', '`');
+ helpers.assertCursorAt(0, 0);
+ var actual = cm.getLine(0);
+ var expected = 'pop pop 0 1 2 3 4';
+ eq(actual, expected, "Deleting while jumping to the next mark failed.");
+});
+testVim('jumpToMark_next_line_action', function(cm, vim, helpers) {
+ cm.setCursor(2, 2);
+ helpers.doKeys('m', 't');
+ cm.setCursor(0, 0);
+ helpers.doKeys('d', ']', '\'');
+ helpers.assertCursorAt(0, 1);
+ var actual = cm.getLine(0);
+ var expected = ' (a) [b] {c} '
+ eq(actual, expected, "Deleting while jumping to the next mark line failed.");
+});
+testVim('jumpToMark_prev', function(cm, vim, helpers) {
+ cm.setCursor(2, 2);
+ helpers.doKeys('m', 't');
+ cm.setCursor(4, 0);
+ helpers.doKeys('[', '`');
+ helpers.assertCursorAt(2, 2);
+ cm.setCursor(4, 0);
+ helpers.doKeys('[', '\'');
+ helpers.assertCursorAt(2, 0);
+});
+testVim('jumpToMark_prev_repeat', function(cm, vim, helpers) {
+ cm.setCursor(2, 2);
+ helpers.doKeys('m', 'a');
+ cm.setCursor(3, 2);
+ helpers.doKeys('m', 'b');
+ cm.setCursor(4, 2);
+ helpers.doKeys('m', 'c');
+ cm.setCursor(5, 0);
+ helpers.doKeys('2', '[', '`');
+ helpers.assertCursorAt(3, 2);
+ cm.setCursor(5, 0);
+ helpers.doKeys('2', '[', '\'');
+ helpers.assertCursorAt(3, 1);
+});
+testVim('jumpToMark_prev_sameline', function(cm, vim, helpers) {
+ cm.setCursor(2, 0);
+ helpers.doKeys('m', 'a');
+ cm.setCursor(2, 4);
+ helpers.doKeys('m', 'b');
+ cm.setCursor(2, 2);
+ helpers.doKeys('[', '`');
+ helpers.assertCursorAt(2, 0);
+});
+testVim('jumpToMark_prev_onlynext', function(cm, vim, helpers) {
+ cm.setCursor(4, 4);
+ helpers.doKeys('m', 'a');
+ cm.setCursor(2, 0);
+ helpers.doKeys('[', '`');
+ helpers.assertCursorAt(2, 0);
+});
+testVim('jumpToMark_prev_nomark', function(cm, vim, helpers) {
+ cm.setCursor(2, 2);
+ helpers.doKeys('[', '`');
+ helpers.assertCursorAt(2, 2);
+ helpers.doKeys('[', '\'');
+ helpers.assertCursorAt(2, 0);
+});
+testVim('jumpToMark_prev_linewise_over', function(cm, vim, helpers) {
+ cm.setCursor(2, 2);
+ helpers.doKeys('m', 'a');
+ cm.setCursor(3, 4);
+ helpers.doKeys('m', 'b');
+ cm.setCursor(3, 6);
+ helpers.doKeys('[', '\'');
+ helpers.assertCursorAt(2, 0);
+});
+testVim('delmark_single', function(cm, vim, helpers) {
+ cm.setCursor(1, 2);
+ helpers.doKeys('m', 't');
+ helpers.doEx('delmarks t');
+ cm.setCursor(0, 0);
+ helpers.doKeys('`', 't');
+ helpers.assertCursorAt(0, 0);
+});
+testVim('delmark_range', function(cm, vim, helpers) {
+ cm.setCursor(1, 2);
+ helpers.doKeys('m', 'a');
+ cm.setCursor(2, 2);
+ helpers.doKeys('m', 'b');
+ cm.setCursor(3, 2);
+ helpers.doKeys('m', 'c');
+ cm.setCursor(4, 2);
+ helpers.doKeys('m', 'd');
+ cm.setCursor(5, 2);
+ helpers.doKeys('m', 'e');
+ helpers.doEx('delmarks b-d');
+ cm.setCursor(0, 0);
+ helpers.doKeys('`', 'a');
+ helpers.assertCursorAt(1, 2);
+ helpers.doKeys('`', 'b');
+ helpers.assertCursorAt(1, 2);
+ helpers.doKeys('`', 'c');
+ helpers.assertCursorAt(1, 2);
+ helpers.doKeys('`', 'd');
+ helpers.assertCursorAt(1, 2);
+ helpers.doKeys('`', 'e');
+ helpers.assertCursorAt(5, 2);
+});
+testVim('delmark_multi', function(cm, vim, helpers) {
+ cm.setCursor(1, 2);
+ helpers.doKeys('m', 'a');
+ cm.setCursor(2, 2);
+ helpers.doKeys('m', 'b');
+ cm.setCursor(3, 2);
+ helpers.doKeys('m', 'c');
+ cm.setCursor(4, 2);
+ helpers.doKeys('m', 'd');
+ cm.setCursor(5, 2);
+ helpers.doKeys('m', 'e');
+ helpers.doEx('delmarks bcd');
+ cm.setCursor(0, 0);
+ helpers.doKeys('`', 'a');
+ helpers.assertCursorAt(1, 2);
+ helpers.doKeys('`', 'b');
+ helpers.assertCursorAt(1, 2);
+ helpers.doKeys('`', 'c');
+ helpers.assertCursorAt(1, 2);
+ helpers.doKeys('`', 'd');
+ helpers.assertCursorAt(1, 2);
+ helpers.doKeys('`', 'e');
+ helpers.assertCursorAt(5, 2);
+});
+testVim('delmark_multi_space', function(cm, vim, helpers) {
+ cm.setCursor(1, 2);
+ helpers.doKeys('m', 'a');
+ cm.setCursor(2, 2);
+ helpers.doKeys('m', 'b');
+ cm.setCursor(3, 2);
+ helpers.doKeys('m', 'c');
+ cm.setCursor(4, 2);
+ helpers.doKeys('m', 'd');
+ cm.setCursor(5, 2);
+ helpers.doKeys('m', 'e');
+ helpers.doEx('delmarks b c d');
+ cm.setCursor(0, 0);
+ helpers.doKeys('`', 'a');
+ helpers.assertCursorAt(1, 2);
+ helpers.doKeys('`', 'b');
+ helpers.assertCursorAt(1, 2);
+ helpers.doKeys('`', 'c');
+ helpers.assertCursorAt(1, 2);
+ helpers.doKeys('`', 'd');
+ helpers.assertCursorAt(1, 2);
+ helpers.doKeys('`', 'e');
+ helpers.assertCursorAt(5, 2);
+});
+testVim('delmark_all', function(cm, vim, helpers) {
+ cm.setCursor(1, 2);
+ helpers.doKeys('m', 'a');
+ cm.setCursor(2, 2);
+ helpers.doKeys('m', 'b');
+ cm.setCursor(3, 2);
+ helpers.doKeys('m', 'c');
+ cm.setCursor(4, 2);
+ helpers.doKeys('m', 'd');
+ cm.setCursor(5, 2);
+ helpers.doKeys('m', 'e');
+ helpers.doEx('delmarks a b-de');
+ cm.setCursor(0, 0);
+ helpers.doKeys('`', 'a');
+ helpers.assertCursorAt(0, 0);
+ helpers.doKeys('`', 'b');
+ helpers.assertCursorAt(0, 0);
+ helpers.doKeys('`', 'c');
+ helpers.assertCursorAt(0, 0);
+ helpers.doKeys('`', 'd');
+ helpers.assertCursorAt(0, 0);
+ helpers.doKeys('`', 'e');
+ helpers.assertCursorAt(0, 0);
+});
+testVim('visual', function(cm, vim, helpers) {
+ helpers.doKeys('l', 'v', 'l', 'l');
+ helpers.assertCursorAt(0, 4);
+ eqCursorPos(makeCursor(0, 1), cm.getCursor('anchor'));
+ helpers.doKeys('d');
+ eq('15', cm.getValue());
+}, { value: '12345' });
+testVim('visual_yank', function(cm, vim, helpers) {
+ helpers.doKeys('v', '3', 'l', 'y');
+ helpers.assertCursorAt(0, 0);
+ helpers.doKeys('p');
+ eq('aa te test for yank', cm.getValue());
+}, { value: 'a test for yank' })
+testVim('visual_w', function(cm, vim, helpers) {
+ helpers.doKeys('v', 'w');
+ eq(cm.getSelection(), 'motion t');
+}, { value: 'motion test'});
+testVim('visual_initial_selection', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.doKeys('v');
+ cm.getSelection('n');
+}, { value: 'init'});
+testVim('visual_crossover_left', function(cm, vim, helpers) {
+ cm.setCursor(0, 2);
+ helpers.doKeys('v', 'l', 'h', 'h');
+ cm.getSelection('ro');
+}, { value: 'cross'});
+testVim('visual_crossover_left', function(cm, vim, helpers) {
+ cm.setCursor(0, 2);
+ helpers.doKeys('v', 'h', 'l', 'l');
+ cm.getSelection('os');
+}, { value: 'cross'});
+testVim('visual_crossover_up', function(cm, vim, helpers) {
+ cm.setCursor(3, 2);
+ helpers.doKeys('v', 'j', 'k', 'k');
+ eqCursorPos(Pos(2, 2), cm.getCursor('head'));
+ eqCursorPos(Pos(3, 3), cm.getCursor('anchor'));
+ helpers.doKeys('k');
+ eqCursorPos(Pos(1, 2), cm.getCursor('head'));
+ eqCursorPos(Pos(3, 3), cm.getCursor('anchor'));
+}, { value: 'cross\ncross\ncross\ncross\ncross\n'});
+testVim('visual_crossover_down', function(cm, vim, helpers) {
+ cm.setCursor(1, 2);
+ helpers.doKeys('v', 'k', 'j', 'j');
+ eqCursorPos(Pos(2, 3), cm.getCursor('head'));
+ eqCursorPos(Pos(1, 2), cm.getCursor('anchor'));
+ helpers.doKeys('j');
+ eqCursorPos(Pos(3, 3), cm.getCursor('head'));
+ eqCursorPos(Pos(1, 2), cm.getCursor('anchor'));
+}, { value: 'cross\ncross\ncross\ncross\ncross\n'});
+testVim('visual_exit', function(cm, vim, helpers) {
+ helpers.doKeys('<C-v>', 'l', 'j', 'j', '<Esc>');
+ eqCursorPos(cm.getCursor('anchor'), cm.getCursor('head'));
+ eq(vim.visualMode, false);
+}, { value: 'hello\nworld\nfoo' });
+testVim('visual_line', function(cm, vim, helpers) {
+ helpers.doKeys('l', 'V', 'l', 'j', 'j', 'd');
+ eq(' 4\n 5', cm.getValue());
+}, { value: ' 1\n 2\n 3\n 4\n 5' });
+testVim('visual_block_move_to_eol', function(cm, vim, helpers) {
+ // moveToEol should move all block cursors to end of line
+ cm.setCursor(0, 0);
+ helpers.doKeys('<C-v>', 'G', '$');
+ var selections = cm.getSelections().join();
+ eq('123,45,6', selections);
+ // Checks that with cursor at Infinity, finding words backwards still works.
+ helpers.doKeys('2', 'k', 'b');
+ selections = cm.getSelections().join();
+ eq('1', selections);
+}, {value: '123\n45\n6'});
+testVim('visual_block_different_line_lengths', function(cm, vim, helpers) {
+ // test the block selection with lines of different length
+ // i.e. extending the selection
+ // till the end of the longest line.
+ helpers.doKeys('<C-v>', 'l', 'j', 'j', '6', 'l', 'd');
+ helpers.doKeys('d', 'd', 'd', 'd');
+ eq('', cm.getValue());
+}, {value: '1234\n5678\nabcdefg'});
+testVim('visual_block_truncate_on_short_line', function(cm, vim, helpers) {
+ // check for left side selection in case
+ // of moving up to a shorter line.
+ cm.replaceRange('', cm.getCursor());
+ cm.setCursor(3, 4);
+ helpers.doKeys('<C-v>', 'l', 'k', 'k', 'd');
+ eq('hello world\n{\ntis\nsa!', cm.getValue());
+}, {value: 'hello world\n{\nthis is\nsparta!'});
+testVim('visual_block_corners', function(cm, vim, helpers) {
+ cm.setCursor(1, 2);
+ helpers.doKeys('<C-v>', '2', 'l', 'k');
+ // circle around the anchor
+ // and check the selections
+ var selections = cm.getSelections();
+ eq('345891', selections.join(''));
+ helpers.doKeys('4', 'h');
+ selections = cm.getSelections();
+ eq('123678', selections.join(''));
+ helpers.doKeys('j', 'j');
+ selections = cm.getSelections();
+ eq('678abc', selections.join(''));
+ helpers.doKeys('4', 'l');
+ selections = cm.getSelections();
+ eq('891cde', selections.join(''));
+}, {value: '12345\n67891\nabcde'});
+testVim('visual_block_mode_switch', function(cm, vim, helpers) {
+ // switch between visual modes
+ cm.setCursor(1, 1);
+ // blockwise to characterwise visual
+ helpers.doKeys('<C-v>', 'j', 'l', 'v');
+ var selections = cm.getSelections();
+ eq('7891\nabc', selections.join(''));
+ // characterwise to blockwise
+ helpers.doKeys('<C-v>');
+ selections = cm.getSelections();
+ eq('78bc', selections.join(''));
+ // blockwise to linewise visual
+ helpers.doKeys('V');
+ selections = cm.getSelections();
+ eq('67891\nabcde', selections.join(''));
+}, {value: '12345\n67891\nabcde'});
+testVim('visual_block_crossing_short_line', function(cm, vim, helpers) {
+ // visual block with long and short lines
+ cm.setCursor(0, 3);
+ helpers.doKeys('<C-v>', 'j', 'j', 'j');
+ var selections = cm.getSelections().join();
+ eq('4,,d,b', selections);
+ helpers.doKeys('3', 'k');
+ selections = cm.getSelections().join();
+ eq('4', selections);
+ helpers.doKeys('5', 'j', 'k');
+ selections = cm.getSelections().join("");
+ eq(10, selections.length);
+}, {value: '123456\n78\nabcdefg\nfoobar\n}\n'});
+testVim('visual_block_curPos_on_exit', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('<C-v>', '3' , 'l', '<Esc>');
+ eqCursorPos(makeCursor(0, 3), cm.getCursor());
+ helpers.doKeys('h', '<C-v>', '2' , 'j' ,'3' , 'l');
+ eq(cm.getSelections().join(), "3456,,cdef");
+ helpers.doKeys('4' , 'h');
+ eq(cm.getSelections().join(), "23,8,bc");
+ helpers.doKeys('2' , 'l');
+ eq(cm.getSelections().join(), "34,,cd");
+}, {value: '123456\n78\nabcdefg\nfoobar'});
+
+testVim('visual_marks', function(cm, vim, helpers) {
+ helpers.doKeys('l', 'v', 'l', 'l', 'j', 'j', 'v');
+ // Test visual mode marks
+ cm.setCursor(2, 1);
+ helpers.doKeys('\'', '<');
+ helpers.assertCursorAt(0, 1);
+ helpers.doKeys('\'', '>');
+ helpers.assertCursorAt(2, 0);
+});
+testVim('visual_join', function(cm, vim, helpers) {
+ helpers.doKeys('l', 'V', 'l', 'j', 'j', 'J');
+ eq(' 1 2 3\n 4\n 5', cm.getValue());
+ is(!vim.visualMode);
+}, { value: ' 1\n 2\n 3\n 4\n 5' });
+testVim('visual_join_2', function(cm, vim, helpers) {
+ helpers.doKeys('G', 'V', 'g', 'g', 'J');
+ eq('1 2 3 4 5 6 ', cm.getValue());
+ is(!vim.visualMode);
+}, { value: '1\n2\n3\n4\n5\n6\n'});
+testVim('visual_blank', function(cm, vim, helpers) {
+ helpers.doKeys('v', 'k');
+ eq(vim.visualMode, true);
+}, { value: '\n' });
+testVim('reselect_visual', function(cm, vim, helpers) {
+ helpers.doKeys('l', 'v', 'l', 'l', 'l', 'y', 'g', 'v');
+ helpers.assertCursorAt(0, 5);
+ eqCursorPos(makeCursor(0, 1), cm.getCursor('anchor'));
+ helpers.doKeys('v');
+ cm.setCursor(1, 0);
+ helpers.doKeys('v', 'l', 'l', 'p');
+ eq('123456\n2345\nbar', cm.getValue());
+ cm.setCursor(0, 0);
+ helpers.doKeys('g', 'v');
+ // here the fake cursor is at (1, 3)
+ helpers.assertCursorAt(1, 4);
+ eqCursorPos(makeCursor(1, 0), cm.getCursor('anchor'));
+ helpers.doKeys('v');
+ cm.setCursor(2, 0);
+ helpers.doKeys('v', 'l', 'l', 'g', 'v');
+ helpers.assertCursorAt(1, 4);
+ eqCursorPos(makeCursor(1, 0), cm.getCursor('anchor'));
+ helpers.doKeys('g', 'v');
+ helpers.assertCursorAt(2, 3);
+ eqCursorPos(makeCursor(2, 0), cm.getCursor('anchor'));
+ eq('123456\n2345\nbar', cm.getValue());
+}, { value: '123456\nfoo\nbar' });
+testVim('reselect_visual_line', function(cm, vim, helpers) {
+ helpers.doKeys('l', 'V', 'j', 'j', 'V', 'g', 'v', 'd');
+ eq('foo\nand\nbar', cm.getValue());
+ cm.setCursor(1, 0);
+ helpers.doKeys('V', 'y', 'j');
+ helpers.doKeys('V', 'p' , 'g', 'v', 'd');
+ eq('foo\nand', cm.getValue());
+}, { value: 'hello\nthis\nis\nfoo\nand\nbar' });
+testVim('reselect_visual_block', function(cm, vim, helpers) {
+ cm.setCursor(1, 2);
+ helpers.doKeys('<C-v>', 'k', 'h', '<C-v>');
+ cm.setCursor(2, 1);
+ helpers.doKeys('v', 'l', 'g', 'v');
+ eqCursorPos(Pos(1, 2), vim.sel.anchor);
+ eqCursorPos(Pos(0, 1), vim.sel.head);
+ // Ensure selection is done with visual block mode rather than one
+ // continuous range.
+ eq(cm.getSelections().join(''), '23oo')
+ helpers.doKeys('g', 'v');
+ eqCursorPos(Pos(2, 1), vim.sel.anchor);
+ eqCursorPos(Pos(2, 2), vim.sel.head);
+ helpers.doKeys('<Esc>');
+ // Ensure selection of deleted range
+ cm.setCursor(1, 1);
+ helpers.doKeys('v', '<C-v>', 'j', 'd', 'g', 'v');
+ eq(cm.getSelections().join(''), 'or');
+}, { value: '123456\nfoo\nbar' });
+testVim('s_normal', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.doKeys('s');
+ helpers.doKeys('<Esc>');
+ eq('ac', cm.getValue());
+}, { value: 'abc'});
+testVim('s_visual', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.doKeys('v', 's');
+ helpers.doKeys('<Esc>');
+ helpers.assertCursorAt(0, 0);
+ eq('ac', cm.getValue());
+}, { value: 'abc'});
+testVim('o_visual', function(cm, vim, helpers) {
+ cm.setCursor(0,0);
+ helpers.doKeys('v','l','l','l','o');
+ helpers.assertCursorAt(0,0);
+ helpers.doKeys('v','v','j','j','j','o');
+ helpers.assertCursorAt(0,0);
+ helpers.doKeys('O');
+ helpers.doKeys('l','l')
+ helpers.assertCursorAt(3, 3);
+ helpers.doKeys('d');
+ eq('p',cm.getValue());
+}, { value: 'abcd\nefgh\nijkl\nmnop'});
+testVim('o_visual_block', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.doKeys('<C-v>','3','j','l','l', 'o');
+ eqCursorPos(Pos(3, 3), vim.sel.anchor);
+ eqCursorPos(Pos(0, 1), vim.sel.head);
+ helpers.doKeys('O');
+ eqCursorPos(Pos(3, 1), vim.sel.anchor);
+ eqCursorPos(Pos(0, 3), vim.sel.head);
+ helpers.doKeys('o');
+ eqCursorPos(Pos(0, 3), vim.sel.anchor);
+ eqCursorPos(Pos(3, 1), vim.sel.head);
+}, { value: 'abcd\nefgh\nijkl\nmnop'});
+testVim('changeCase_visual', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('v', 'l', 'l');
+ helpers.doKeys('U');
+ helpers.assertCursorAt(0, 0);
+ helpers.doKeys('v', 'l', 'l');
+ helpers.doKeys('u');
+ helpers.assertCursorAt(0, 0);
+ helpers.doKeys('l', 'l', 'l', '.');
+ helpers.assertCursorAt(0, 3);
+ cm.setCursor(0, 0);
+ helpers.doKeys('q', 'a', 'v', 'j', 'U', 'q');
+ helpers.assertCursorAt(0, 0);
+ helpers.doKeys('j', '@', 'a');
+ helpers.assertCursorAt(1, 0);
+ cm.setCursor(3, 0);
+ helpers.doKeys('V', 'U', 'j', '.');
+ eq('ABCDEF\nGHIJKL\nMnopq\nSHORT LINE\nLONG LINE OF TEXT', cm.getValue());
+}, { value: 'abcdef\nghijkl\nmnopq\nshort line\nlong line of text'});
+testVim('changeCase_visual_block', function(cm, vim, helpers) {
+ cm.setCursor(2, 1);
+ helpers.doKeys('<C-v>', 'k', 'k', 'h', 'U');
+ eq('ABcdef\nGHijkl\nMNopq\nfoo', cm.getValue());
+ cm.setCursor(0, 2);
+ helpers.doKeys('.');
+ eq('ABCDef\nGHIJkl\nMNOPq\nfoo', cm.getValue());
+ // check when last line is shorter.
+ cm.setCursor(2, 2);
+ helpers.doKeys('.');
+ eq('ABCDef\nGHIJkl\nMNOPq\nfoO', cm.getValue());
+}, { value: 'abcdef\nghijkl\nmnopq\nfoo'});
+testVim('visual_paste', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('v', 'l', 'l', 'y');
+ helpers.assertCursorAt(0, 0);
+ helpers.doKeys('3', 'l', 'j', 'v', 'l', 'p');
+ helpers.assertCursorAt(1, 5);
+ eq('this is a\nunithitest for visual paste', cm.getValue());
+ cm.setCursor(0, 0);
+ // in case of pasting whole line
+ helpers.doKeys('y', 'y');
+ cm.setCursor(1, 6);
+ helpers.doKeys('v', 'l', 'l', 'l', 'p');
+ helpers.assertCursorAt(2, 0);
+ eq('this is a\nunithi\nthis is a\n for visual paste', cm.getValue());
+}, { value: 'this is a\nunit test for visual paste'});
+
+// This checks the contents of the register used to paste the text
+testVim('v_paste_from_register', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('"', 'a', 'y', 'w');
+ cm.setCursor(1, 0);
+ helpers.doKeys('v', 'p');
+ cm.openDialog = helpers.fakeOpenDialog('registers');
+ cm.openNotification = helpers.fakeOpenNotification(function(text) {
+ is(/a\s+register/.test(text));
+ });
+}, { value: 'register contents\nare not erased'});
+testVim('S_normal', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.doKeys('j', 'S');
+ helpers.doKeys('<Esc>');
+ helpers.assertCursorAt(1, 1);
+ eq('aa{\n \ncc', cm.getValue());
+ helpers.doKeys('j', 'S');
+ eq('aa{\n \n ', cm.getValue());
+ helpers.assertCursorAt(2, 2);
+ helpers.doKeys('<Esc>');
+ helpers.doKeys('d', 'd', 'd', 'd');
+ helpers.assertCursorAt(0, 0);
+ helpers.doKeys('S');
+ is(vim.insertMode);
+ eq('', cm.getValue());
+}, { value: 'aa{\nbb\ncc'});
+testVim('blockwise_paste', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('<C-v>', '3', 'j', 'l', 'y');
+ cm.setCursor(0, 2);
+ // paste one char after the current cursor position
+ helpers.doKeys('p');
+ eq('helhelo\nworwold\nfoofo\nbarba', cm.getValue());
+ cm.setCursor(0, 0);
+ helpers.doKeys('v', '4', 'l', 'y');
+ cm.setCursor(0, 0);
+ helpers.doKeys('<C-v>', '3', 'j', 'p');
+ eq('helheelhelo\norwold\noofo\narba', cm.getValue());
+}, { value: 'hello\nworld\nfoo\nbar'});
+testVim('blockwise_paste_long/short_line', function(cm, vim, helpers) {
+ // extend short lines in case of different line lengths.
+ cm.setCursor(0, 0);
+ helpers.doKeys('<C-v>', 'j', 'j', 'y');
+ cm.setCursor(0, 3);
+ helpers.doKeys('p');
+ eq('hellho\nfoo f\nbar b', cm.getValue());
+}, { value: 'hello\nfoo\nbar'});
+testVim('blockwise_paste_cut_paste', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('<C-v>', '2', 'j', 'x');
+ cm.setCursor(0, 0);
+ helpers.doKeys('P');
+ eq('cut\nand\npaste\nme', cm.getValue());
+}, { value: 'cut\nand\npaste\nme'});
+testVim('blockwise_paste_from_register', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('<C-v>', '2', 'j', '"', 'a', 'y');
+ cm.setCursor(0, 3);
+ helpers.doKeys('"', 'a', 'p');
+ eq('foobfar\nhellho\nworlwd', cm.getValue());
+}, { value: 'foobar\nhello\nworld'});
+testVim('blockwise_paste_last_line', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('<C-v>', '2', 'j', 'l', 'y');
+ cm.setCursor(3, 0);
+ helpers.doKeys('p');
+ eq('cut\nand\npaste\nmcue\n an\n pa', cm.getValue());
+}, { value: 'cut\nand\npaste\nme'});
+
+testVim('S_visual', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.doKeys('v', 'j', 'S');
+ helpers.doKeys('<Esc>');
+ helpers.assertCursorAt(0, 0);
+ eq('\ncc', cm.getValue());
+}, { value: 'aa\nbb\ncc'});
+
+testVim('d_/', function(cm, vim, helpers) {
+ cm.openDialog = helpers.fakeOpenDialog('match');
+ helpers.doKeys('2', 'd', '/');
+ helpers.assertCursorAt(0, 0);
+ eq('match \n next', cm.getValue());
+ cm.openDialog = helpers.fakeOpenDialog('2');
+ helpers.doKeys('d', ':');
+ // TODO eq(' next', cm.getValue());
+}, { value: 'text match match \n next' });
+testVim('/ and n/N', function(cm, vim, helpers) {
+ cm.openDialog = helpers.fakeOpenDialog('match');
+ helpers.doKeys('/');
+ helpers.assertCursorAt(0, 11);
+ helpers.doKeys('n');
+ helpers.assertCursorAt(1, 6);
+ helpers.doKeys('N');
+ helpers.assertCursorAt(0, 11);
+
+ cm.setCursor(0, 0);
+ helpers.doKeys('2', '/');
+ helpers.assertCursorAt(1, 6);
+}, { value: 'match nope match \n nope Match' });
+testVim('/_case', function(cm, vim, helpers) {
+ cm.openDialog = helpers.fakeOpenDialog('Match');
+ helpers.doKeys('/');
+ helpers.assertCursorAt(1, 6);
+}, { value: 'match nope match \n nope Match' });
+testVim('/_2_pcre', function(cm, vim, helpers) {
+ CodeMirror.Vim.setOption('pcre', true);
+ cm.openDialog = helpers.fakeOpenDialog('(word){2}');
+ helpers.doKeys('/');
+ helpers.assertCursorAt(1, 9);
+ helpers.doKeys('n');
+ helpers.assertCursorAt(2, 1);
+}, { value: 'word\n another wordword\n wordwordword\n' });
+testVim('/_2_nopcre', function(cm, vim, helpers) {
+ CodeMirror.Vim.setOption('pcre', false);
+ cm.openDialog = helpers.fakeOpenDialog('\\(word\\)\\{2}');
+ helpers.doKeys('/');
+ helpers.assertCursorAt(1, 9);
+ helpers.doKeys('n');
+ helpers.assertCursorAt(2, 1);
+}, { value: 'word\n another wordword\n wordwordword\n' });
+testVim('/_nongreedy', function(cm, vim, helpers) {
+ cm.openDialog = helpers.fakeOpenDialog('aa');
+ helpers.doKeys('/');
+ helpers.assertCursorAt(0, 4);
+ helpers.doKeys('n');
+ helpers.assertCursorAt(1, 3);
+ helpers.doKeys('n');
+ helpers.assertCursorAt(0, 0);
+}, { value: 'aaa aa \n a aa'});
+testVim('?_nongreedy', function(cm, vim, helpers) {
+ cm.openDialog = helpers.fakeOpenDialog('aa');
+ helpers.doKeys('?');
+ helpers.assertCursorAt(1, 3);
+ helpers.doKeys('n');
+ helpers.assertCursorAt(0, 4);
+ helpers.doKeys('n');
+ helpers.assertCursorAt(0, 0);
+}, { value: 'aaa aa \n a aa'});
+testVim('/_greedy', function(cm, vim, helpers) {
+ cm.openDialog = helpers.fakeOpenDialog('a+');
+ helpers.doKeys('/');
+ helpers.assertCursorAt(0, 4);
+ helpers.doKeys('n');
+ helpers.assertCursorAt(1, 1);
+ helpers.doKeys('n');
+ helpers.assertCursorAt(1, 3);
+ helpers.doKeys('n');
+ helpers.assertCursorAt(0, 0);
+}, { value: 'aaa aa \n a aa'});
+testVim('?_greedy', function(cm, vim, helpers) {
+ cm.openDialog = helpers.fakeOpenDialog('a+');
+ helpers.doKeys('?');
+ helpers.assertCursorAt(1, 3);
+ helpers.doKeys('n');
+ helpers.assertCursorAt(1, 1);
+ helpers.doKeys('n');
+ helpers.assertCursorAt(0, 4);
+ helpers.doKeys('n');
+ helpers.assertCursorAt(0, 0);
+}, { value: 'aaa aa \n a aa'});
+testVim('/_greedy_0_or_more', function(cm, vim, helpers) {
+ cm.openDialog = helpers.fakeOpenDialog('a*');
+ helpers.doKeys('/');
+ helpers.assertCursorAt(0, 3);
+ helpers.doKeys('n');
+ helpers.assertCursorAt(0, 4);
+ helpers.doKeys('n');
+ helpers.assertCursorAt(0, 5);
+ helpers.doKeys('n');
+ helpers.assertCursorAt(1, 0);
+ helpers.doKeys('n');
+ helpers.assertCursorAt(1, 1);
+ helpers.doKeys('n');
+ helpers.assertCursorAt(0, 0);
+}, { value: 'aaa aa\n aa'});
+testVim('?_greedy_0_or_more', function(cm, vim, helpers) {
+ cm.openDialog = helpers.fakeOpenDialog('a*');
+ helpers.doKeys('?');
+ helpers.assertCursorAt(1, 1);
+ helpers.doKeys('n');
+ helpers.assertCursorAt(0, 5);
+ helpers.doKeys('n');
+ helpers.assertCursorAt(0, 3);
+ helpers.doKeys('n');
+ helpers.assertCursorAt(0, 0);
+}, { value: 'aaa aa\n aa'});
+testVim('? and n/N', function(cm, vim, helpers) {
+ cm.openDialog = helpers.fakeOpenDialog('match');
+ helpers.doKeys('?');
+ helpers.assertCursorAt(1, 6);
+ helpers.doKeys('n');
+ helpers.assertCursorAt(0, 11);
+ helpers.doKeys('N');
+ helpers.assertCursorAt(1, 6);
+
+ cm.setCursor(0, 0);
+ helpers.doKeys('2', '?');
+ helpers.assertCursorAt(0, 11);
+}, { value: 'match nope match \n nope Match' });
+testVim('*', function(cm, vim, helpers) {
+ cm.setCursor(0, 9);
+ helpers.doKeys('*');
+ helpers.assertCursorAt(0, 22);
+
+ cm.setCursor(0, 9);
+ helpers.doKeys('2', '*');
+ helpers.assertCursorAt(1, 8);
+}, { value: 'nomatch match nomatch match \nnomatch Match' });
+testVim('*_no_word', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('*');
+ helpers.assertCursorAt(0, 0);
+}, { value: ' \n match \n' });
+testVim('*_symbol', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('*');
+ helpers.assertCursorAt(1, 0);
+}, { value: ' /}\n/} match \n' });
+testVim('#', function(cm, vim, helpers) {
+ cm.setCursor(0, 9);
+ helpers.doKeys('#');
+ helpers.assertCursorAt(1, 8);
+
+ cm.setCursor(0, 9);
+ helpers.doKeys('2', '#');
+ helpers.assertCursorAt(0, 22);
+}, { value: 'nomatch match nomatch match \nnomatch Match' });
+testVim('*_seek', function(cm, vim, helpers) {
+ // Should skip over space and symbols.
+ cm.setCursor(0, 3);
+ helpers.doKeys('*');
+ helpers.assertCursorAt(0, 22);
+}, { value: ' := match nomatch match \nnomatch Match' });
+testVim('#', function(cm, vim, helpers) {
+ // Should skip over space and symbols.
+ cm.setCursor(0, 3);
+ helpers.doKeys('#');
+ helpers.assertCursorAt(1, 8);
+}, { value: ' := match nomatch match \nnomatch Match' });
+testVim('g*', function(cm, vim, helpers) {
+ cm.setCursor(0, 8);
+ helpers.doKeys('g', '*');
+ helpers.assertCursorAt(0, 18);
+ cm.setCursor(0, 8);
+ helpers.doKeys('3', 'g', '*');
+ helpers.assertCursorAt(1, 8);
+}, { value: 'matches match alsoMatch\nmatchme matching' });
+testVim('g#', function(cm, vim, helpers) {
+ cm.setCursor(0, 8);
+ helpers.doKeys('g', '#');
+ helpers.assertCursorAt(0, 0);
+ cm.setCursor(0, 8);
+ helpers.doKeys('3', 'g', '#');
+ helpers.assertCursorAt(1, 0);
+}, { value: 'matches match alsoMatch\nmatchme matching' });
+testVim('macro_insert', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('q', 'a', '0', 'i');
+ helpers.doKeys('foo')
+ helpers.doKeys('<Esc>');
+ helpers.doKeys('q', '@', 'a');
+ eq('foofoo', cm.getValue());
+}, { value: ''});
+testVim('macro_insert_repeat', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('q', 'a', '$', 'a');
+ helpers.doKeys('larry.')
+ helpers.doKeys('<Esc>');
+ helpers.doKeys('a');
+ helpers.doKeys('curly.')
+ helpers.doKeys('<Esc>');
+ helpers.doKeys('q');
+ helpers.doKeys('a');
+ helpers.doKeys('moe.')
+ helpers.doKeys('<Esc>');
+ helpers.doKeys('@', 'a');
+ // At this point, the most recent edit should be the 2nd insert change
+ // inside the macro, i.e. "curly.".
+ helpers.doKeys('.');
+ eq('larry.curly.moe.larry.curly.curly.', cm.getValue());
+}, { value: ''});
+testVim('macro_space', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('<Space>', '<Space>');
+ helpers.assertCursorAt(0, 2);
+ helpers.doKeys('q', 'a', '<Space>', '<Space>', 'q');
+ helpers.assertCursorAt(0, 4);
+ helpers.doKeys('@', 'a');
+ helpers.assertCursorAt(0, 6);
+ helpers.doKeys('@', 'a');
+ helpers.assertCursorAt(0, 8);
+}, { value: 'one line of text.'});
+testVim('macro_t_search', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('q', 'a', 't', 'e', 'q');
+ helpers.assertCursorAt(0, 1);
+ helpers.doKeys('l', '@', 'a');
+ helpers.assertCursorAt(0, 6);
+ helpers.doKeys('l', ';');
+ helpers.assertCursorAt(0, 12);
+}, { value: 'one line of text.'});
+testVim('macro_f_search', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('q', 'b', 'f', 'e', 'q');
+ helpers.assertCursorAt(0, 2);
+ helpers.doKeys('@', 'b');
+ helpers.assertCursorAt(0, 7);
+ helpers.doKeys(';');
+ helpers.assertCursorAt(0, 13);
+}, { value: 'one line of text.'});
+testVim('macro_slash_search', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('q', 'c');
+ cm.openDialog = helpers.fakeOpenDialog('e');
+ helpers.doKeys('/', 'q');
+ helpers.assertCursorAt(0, 2);
+ helpers.doKeys('@', 'c');
+ helpers.assertCursorAt(0, 7);
+ helpers.doKeys('n');
+ helpers.assertCursorAt(0, 13);
+}, { value: 'one line of text.'});
+testVim('macro_multislash_search', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('q', 'd');
+ cm.openDialog = helpers.fakeOpenDialog('e');
+ helpers.doKeys('/');
+ cm.openDialog = helpers.fakeOpenDialog('t');
+ helpers.doKeys('/', 'q');
+ helpers.assertCursorAt(0, 12);
+ helpers.doKeys('@', 'd');
+ helpers.assertCursorAt(0, 15);
+}, { value: 'one line of text to rule them all.'});
+testVim('macro_last_ex_command_register', function (cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doEx('s/a/b');
+ helpers.doKeys('2', '@', ':');
+ eq('bbbaa', cm.getValue());
+ helpers.assertCursorAt(0, 2);
+}, { value: 'aaaaa'});
+testVim('macro_last_run_macro', function (cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('q', 'a', 'C', 'a', '<Esc>', 'q');
+ helpers.doKeys('q', 'b', 'C', 'b', '<Esc>', 'q');
+ helpers.doKeys('@', 'a');
+ helpers.doKeys('d', 'd');
+ helpers.doKeys('@', '@');
+ eq('a', cm.getValue());
+}, { value: ''});
+testVim('macro_parens', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('q', 'z', 'i');
+ helpers.doKeys('(')
+ helpers.doKeys('<Esc>');
+ helpers.doKeys('e', 'a');
+ helpers.doKeys(')')
+ helpers.doKeys('<Esc>');
+ helpers.doKeys('q');
+ helpers.doKeys('w', '@', 'z');
+ helpers.doKeys('w', '@', 'z');
+ eq('(see) (spot) (run)', cm.getValue());
+}, { value: 'see spot run'});
+testVim('macro_overwrite', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('q', 'z', '0', 'i');
+ helpers.doKeys('I ')
+ helpers.doKeys('<Esc>');
+ helpers.doKeys('q');
+ helpers.doKeys('e');
+ // Now replace the macro with something else.
+ helpers.doKeys('q', 'z', 'a');
+ helpers.doKeys('.')
+ helpers.doKeys('<Esc>');
+ helpers.doKeys('q');
+ helpers.doKeys('e', '@', 'z');
+ helpers.doKeys('e', '@', 'z');
+ eq('I see. spot. run.', cm.getValue());
+}, { value: 'see spot run'});
+testVim('macro_search_f', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('q', 'a', 'f', ' ');
+ helpers.assertCursorAt(0,3);
+ helpers.doKeys('q', '0');
+ helpers.assertCursorAt(0,0);
+ helpers.doKeys('@', 'a');
+ helpers.assertCursorAt(0,3);
+}, { value: 'The quick brown fox jumped over the lazy dog.'});
+testVim('macro_search_2f', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('q', 'a', '2', 'f', ' ');
+ helpers.assertCursorAt(0,9);
+ helpers.doKeys('q', '0');
+ helpers.assertCursorAt(0,0);
+ helpers.doKeys('@', 'a');
+ helpers.assertCursorAt(0,9);
+}, { value: 'The quick brown fox jumped over the lazy dog.'});
+testVim('macro_yank_tick', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ // Start recording a macro into the \' register.
+ helpers.doKeys('q', '\'');
+ helpers.doKeys('y', '<Right>', '<Right>', '<Right>', '<Right>', 'p');
+ helpers.assertCursorAt(0,4);
+ eq('the tex parrot', cm.getValue());
+}, { value: 'the ex parrot'});
+testVim('yank_register', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('"', 'a', 'y', 'y');
+ helpers.doKeys('j', '"', 'b', 'y', 'y');
+ cm.openDialog = helpers.fakeOpenDialog('registers');
+ cm.openNotification = helpers.fakeOpenNotification(function(text) {
+ is(/a\s+foo/.test(text));
+ is(/b\s+bar/.test(text));
+ });
+ helpers.doKeys(':');
+}, { value: 'foo\nbar'});
+testVim('yank_visual_block', function(cm, vim, helpers) {
+ cm.setCursor(0, 1);
+ helpers.doKeys('<C-v>', 'l', 'j', '"', 'a', 'y');
+ cm.openNotification = helpers.fakeOpenNotification(function(text) {
+ is(/a\s+oo\nar/.test(text));
+ });
+ helpers.doKeys(':');
+}, { value: 'foo\nbar'});
+testVim('yank_append_line_to_line_register', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('"', 'a', 'y', 'y');
+ helpers.doKeys('j', '"', 'A', 'y', 'y');
+ cm.openDialog = helpers.fakeOpenDialog('registers');
+ cm.openNotification = helpers.fakeOpenNotification(function(text) {
+ is(/a\s+foo\nbar/.test(text));
+ is(/"\s+foo\nbar/.test(text));
+ });
+ helpers.doKeys(':');
+}, { value: 'foo\nbar'});
+testVim('yank_append_word_to_word_register', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('"', 'a', 'y', 'w');
+ helpers.doKeys('j', '"', 'A', 'y', 'w');
+ cm.openDialog = helpers.fakeOpenDialog('registers');
+ cm.openNotification = helpers.fakeOpenNotification(function(text) {
+ is(/a\s+foobar/.test(text));
+ is(/"\s+foobar/.test(text));
+ });
+ helpers.doKeys(':');
+}, { value: 'foo\nbar'});
+testVim('yank_append_line_to_word_register', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('"', 'a', 'y', 'w');
+ helpers.doKeys('j', '"', 'A', 'y', 'y');
+ cm.openDialog = helpers.fakeOpenDialog('registers');
+ cm.openNotification = helpers.fakeOpenNotification(function(text) {
+ is(/a\s+foo\nbar/.test(text));
+ is(/"\s+foo\nbar/.test(text));
+ });
+ helpers.doKeys(':');
+}, { value: 'foo\nbar'});
+testVim('yank_append_word_to_line_register', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('"', 'a', 'y', 'y');
+ helpers.doKeys('j', '"', 'A', 'y', 'w');
+ cm.openDialog = helpers.fakeOpenDialog('registers');
+ cm.openNotification = helpers.fakeOpenNotification(function(text) {
+ is(/a\s+foo\nbar/.test(text));
+ is(/"\s+foo\nbar/.test(text));
+ });
+ helpers.doKeys(':');
+}, { value: 'foo\nbar'});
+testVim('macro_register', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('q', 'a', 'i');
+ helpers.doKeys('gangnam')
+ helpers.doKeys('<Esc>');
+ helpers.doKeys('q');
+ helpers.doKeys('q', 'b', 'o');
+ helpers.doKeys('style')
+ helpers.doKeys('<Esc>');
+ helpers.doKeys('q');
+ cm.openDialog = helpers.fakeOpenDialog('registers');
+ cm.openNotification = helpers.fakeOpenNotification(function(text) {
+ is(/a\s+i/.test(text));
+ is(/b\s+o/.test(text));
+ });
+ helpers.doKeys(':');
+}, { value: ''});
+testVim('._register', function(cm,vim,helpers) {
+ cm.setCursor(0,0);
+ helpers.doKeys('i');
+ helpers.doKeys('foo')
+ helpers.doKeys('<Esc>');
+ cm.openDialog = helpers.fakeOpenDialog('registers');
+ cm.openNotification = helpers.fakeOpenNotification(function(text) {
+ is(/\.\s+foo/.test(text));
+ });
+ helpers.doKeys(':');
+}, {value: ''});
+testVim(':_register', function(cm,vim,helpers) {
+ helpers.doEx('bar');
+ cm.openDialog = helpers.fakeOpenDialog('registers');
+ cm.openNotification = helpers.fakeOpenNotification(function(text) {
+ is(/:\s+bar/.test(text));
+ });
+ helpers.doKeys(':');
+}, {value: ''});
+testVim('search_register_escape', function(cm, vim, helpers) {
+ // Check that the register is restored if the user escapes rather than confirms.
+ cm.openDialog = helpers.fakeOpenDialog('waldo');
+ helpers.doKeys('/');
+ var onKeyDown;
+ var onKeyUp;
+ var KEYCODES = {
+ f: 70,
+ o: 79,
+ Esc: 27
+ };
+ cm.openDialog = function(template, callback, options) {
+ onKeyDown = options.onKeyDown;
+ onKeyUp = options.onKeyUp;
+ };
+ var close = function() {};
+ helpers.doKeys('/');
+ // Fake some keyboard events coming in.
+ onKeyDown({keyCode: KEYCODES.f}, '', close);
+ onKeyUp({keyCode: KEYCODES.f}, '', close);
+ onKeyDown({keyCode: KEYCODES.o}, 'f', close);
+ onKeyUp({keyCode: KEYCODES.o}, 'f', close);
+ onKeyDown({keyCode: KEYCODES.o}, 'fo', close);
+ onKeyUp({keyCode: KEYCODES.o}, 'fo', close);
+ onKeyDown({keyCode: KEYCODES.Esc}, 'foo', close);
+ cm.openDialog = helpers.fakeOpenDialog('registers');
+ cm.openNotification = helpers.fakeOpenNotification(function(text) {
+ is(/waldo/.test(text));
+ is(!/foo/.test(text));
+ });
+ helpers.doKeys(':');
+}, {value: ''});
+testVim('search_register', function(cm, vim, helpers) {
+ cm.openDialog = helpers.fakeOpenDialog('foo');
+ helpers.doKeys('/');
+ cm.openDialog = helpers.fakeOpenDialog('registers');
+ cm.openNotification = helpers.fakeOpenNotification(function(text) {
+ is(/\/\s+foo/.test(text));
+ });
+ helpers.doKeys(':');
+}, {value: ''});
+testVim('search_history', function(cm, vim, helpers) {
+ cm.openDialog = helpers.fakeOpenDialog('this');
+ helpers.doKeys('/');
+ cm.openDialog = helpers.fakeOpenDialog('checks');
+ helpers.doKeys('/');
+ cm.openDialog = helpers.fakeOpenDialog('search');
+ helpers.doKeys('/');
+ cm.openDialog = helpers.fakeOpenDialog('history');
+ helpers.doKeys('/');
+ cm.openDialog = helpers.fakeOpenDialog('checks');
+ helpers.doKeys('/');
+ var onKeyDown;
+ var onKeyUp;
+ var query = '';
+ var keyCodes = {
+ Up: 38,
+ Down: 40
+ };
+ cm.openDialog = function(template, callback, options) {
+ onKeyUp = options.onKeyUp;
+ onKeyDown = options.onKeyDown;
+ };
+ var close = function(newVal) {
+ if (typeof newVal == 'string') query = newVal;
+ }
+ helpers.doKeys('/');
+ onKeyDown({keyCode: keyCodes.Up}, query, close);
+ onKeyUp({keyCode: keyCodes.Up}, query, close);
+ eq(query, 'checks');
+ onKeyDown({keyCode: keyCodes.Up}, query, close);
+ onKeyUp({keyCode: keyCodes.Up}, query, close);
+ eq(query, 'history');
+ onKeyDown({keyCode: keyCodes.Up}, query, close);
+ onKeyUp({keyCode: keyCodes.Up}, query, close);
+ eq(query, 'search');
+ onKeyDown({keyCode: keyCodes.Up}, query, close);
+ onKeyUp({keyCode: keyCodes.Up}, query, close);
+ eq(query, 'this');
+ onKeyDown({keyCode: keyCodes.Down}, query, close);
+ onKeyUp({keyCode: keyCodes.Down}, query, close);
+ eq(query, 'search');
+}, {value: ''});
+testVim('exCommand_history', function(cm, vim, helpers) {
+ cm.openDialog = helpers.fakeOpenDialog('registers');
+ helpers.doKeys(':');
+ cm.openDialog = helpers.fakeOpenDialog('sort');
+ helpers.doKeys(':');
+ cm.openDialog = helpers.fakeOpenDialog('map');
+ helpers.doKeys(':');
+ cm.openDialog = helpers.fakeOpenDialog('invalid');
+ helpers.doKeys(':');
+ var onKeyDown;
+ var onKeyUp;
+ var input = '';
+ var keyCodes = {
+ Up: 38,
+ Down: 40,
+ s: 115
+ };
+ cm.openDialog = function(template, callback, options) {
+ onKeyUp = options.onKeyUp;
+ onKeyDown = options.onKeyDown;
+ };
+ var close = function(newVal) {
+ if (typeof newVal == 'string') input = newVal;
+ }
+ helpers.doKeys(':');
+ onKeyDown({keyCode: keyCodes.Up}, input, close);
+ eq(input, 'invalid');
+ onKeyDown({keyCode: keyCodes.Up}, input, close);
+ eq(input, 'map');
+ onKeyDown({keyCode: keyCodes.Up}, input, close);
+ eq(input, 'sort');
+ onKeyDown({keyCode: keyCodes.Up}, input, close);
+ eq(input, 'registers');
+ onKeyDown({keyCode: keyCodes.s}, '', close);
+ input = 's';
+ onKeyDown({keyCode: keyCodes.Up}, input, close);
+ eq(input, 'sort');
+}, {value: ''});
+testVim('search_clear', function(cm, vim, helpers) {
+ var onKeyDown;
+ var input = '';
+ var keyCodes = {
+ Ctrl: 17,
+ u: 85
+ };
+ cm.openDialog = function(template, callback, options) {
+ onKeyDown = options.onKeyDown;
+ };
+ var close = function(newVal) {
+ if (typeof newVal == 'string') input = newVal;
+ }
+ helpers.doKeys('/');
+ input = 'foo';
+ onKeyDown({keyCode: keyCodes.Ctrl}, input, close);
+ onKeyDown({keyCode: keyCodes.u, ctrlKey: true}, input, close);
+ eq(input, '');
+});
+testVim('exCommand_clear', function(cm, vim, helpers) {
+ var onKeyDown;
+ var input = '';
+ var keyCodes = {
+ Ctrl: 17,
+ u: 85
+ };
+ cm.openDialog = function(template, callback, options) {
+ onKeyDown = options.onKeyDown;
+ };
+ var close = function(newVal) {
+ if (typeof newVal == 'string') input = newVal;
+ }
+ helpers.doKeys(':');
+ input = 'foo';
+ onKeyDown({keyCode: keyCodes.Ctrl}, input, close);
+ onKeyDown({keyCode: keyCodes.u, ctrlKey: true}, input, close);
+ eq(input, '');
+});
+testVim('.', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('2', 'd', 'w');
+ helpers.doKeys('.');
+ eq('5 6', cm.getValue());
+}, { value: '1 2 3 4 5 6'});
+testVim('._repeat', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('2', 'd', 'w');
+ helpers.doKeys('3', '.');
+ eq('6', cm.getValue());
+}, { value: '1 2 3 4 5 6'});
+testVim('._insert', function(cm, vim, helpers) {
+ helpers.doKeys('i');
+ helpers.doKeys('test')
+ helpers.doKeys('<Esc>');
+ helpers.doKeys('.');
+ eq('testestt', cm.getValue());
+ helpers.assertCursorAt(0, 6);
+ helpers.doKeys('O');
+ helpers.doKeys('xyz')
+ helpers.doInsertModeKeys('Backspace');
+ helpers.doInsertModeKeys('Down');
+ helpers.doKeys('<Esc>');
+ helpers.doKeys('.');
+ eq('xy\nxy\ntestestt', cm.getValue());
+ helpers.assertCursorAt(1, 1);
+}, { value: ''});
+testVim('._insert_repeat', function(cm, vim, helpers) {
+ helpers.doKeys('i');
+ helpers.doKeys('test')
+ cm.setCursor(0, 4);
+ helpers.doKeys('<Esc>');
+ helpers.doKeys('2', '.');
+ eq('testesttestt', cm.getValue());
+ helpers.assertCursorAt(0, 10);
+}, { value: ''});
+testVim('._repeat_insert', function(cm, vim, helpers) {
+ helpers.doKeys('3', 'i');
+ helpers.doKeys('te')
+ cm.setCursor(0, 2);
+ helpers.doKeys('<Esc>');
+ helpers.doKeys('.');
+ eq('tetettetetee', cm.getValue());
+ helpers.assertCursorAt(0, 10);
+}, { value: ''});
+testVim('._insert_o', function(cm, vim, helpers) {
+ helpers.doKeys('o');
+ helpers.doKeys('z')
+ cm.setCursor(1, 1);
+ helpers.doKeys('<Esc>');
+ helpers.doKeys('.');
+ eq('\nz\nz', cm.getValue());
+ helpers.assertCursorAt(2, 0);
+}, { value: ''});
+testVim('._insert_o_repeat', function(cm, vim, helpers) {
+ helpers.doKeys('o');
+ helpers.doKeys('z')
+ helpers.doKeys('<Esc>');
+ cm.setCursor(1, 0);
+ helpers.doKeys('2', '.');
+ eq('\nz\nz\nz', cm.getValue());
+ helpers.assertCursorAt(3, 0);
+}, { value: ''});
+testVim('._insert_o_indent', function(cm, vim, helpers) {
+ helpers.doKeys('o');
+ helpers.doKeys('z')
+ helpers.doKeys('<Esc>');
+ cm.setCursor(1, 2);
+ helpers.doKeys('.');
+ eq('{\n z\n z', cm.getValue());
+ helpers.assertCursorAt(2, 2);
+}, { value: '{'});
+testVim('._insert_cw', function(cm, vim, helpers) {
+ helpers.doKeys('c', 'w');
+ helpers.doKeys('test')
+ helpers.doKeys('<Esc>');
+ cm.setCursor(0, 3);
+ helpers.doKeys('2', 'l');
+ helpers.doKeys('.');
+ eq('test test word3', cm.getValue());
+ helpers.assertCursorAt(0, 8);
+}, { value: 'word1 word2 word3' });
+testVim('._insert_cw_repeat', function(cm, vim, helpers) {
+ // For some reason, repeat cw in desktop VIM will does not repeat insert mode
+ // changes. Will conform to that behavior.
+ helpers.doKeys('c', 'w');
+ helpers.doKeys('test');
+ helpers.doKeys('<Esc>');
+ cm.setCursor(0, 4);
+ helpers.doKeys('l');
+ helpers.doKeys('2', '.');
+ eq('test test', cm.getValue());
+ helpers.assertCursorAt(0, 8);
+}, { value: 'word1 word2 word3' });
+testVim('._delete', function(cm, vim, helpers) {
+ cm.setCursor(0, 5);
+ helpers.doKeys('i');
+ helpers.doInsertModeKeys('Backspace');
+ helpers.doKeys('<Esc>');
+ helpers.doKeys('.');
+ eq('zace', cm.getValue());
+ helpers.assertCursorAt(0, 1);
+}, { value: 'zabcde'});
+testVim('._delete_repeat', function(cm, vim, helpers) {
+ cm.setCursor(0, 6);
+ helpers.doKeys('i');
+ helpers.doInsertModeKeys('Backspace');
+ helpers.doKeys('<Esc>');
+ helpers.doKeys('2', '.');
+ eq('zzce', cm.getValue());
+ helpers.assertCursorAt(0, 1);
+}, { value: 'zzabcde'});
+testVim('._visual_>', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('V', 'j', '>');
+ cm.setCursor(2, 0)
+ helpers.doKeys('.');
+ eq(' 1\n 2\n 3\n 4', cm.getValue());
+ helpers.assertCursorAt(2, 2);
+}, { value: '1\n2\n3\n4'});
+testVim('._replace_repeat', function(cm, vim, helpers) {
+ helpers.doKeys('R');
+ cm.replaceRange('123', cm.getCursor(), offsetCursor(cm.getCursor(), 0, 3));
+ cm.setCursor(0, 3);
+ helpers.doKeys('<Esc>');
+ helpers.doKeys('2', '.');
+ eq('12123123\nabcdefg', cm.getValue());
+ helpers.assertCursorAt(0, 7);
+ cm.setCursor(1, 0);
+ helpers.doKeys('.');
+ eq('12123123\n123123g', cm.getValue());
+ helpers.doKeys('l', '"', '.', 'p');
+ eq('12123123\n123123g123', cm.getValue());
+}, { value: 'abcdef\nabcdefg'});
+testVim('f;', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('f', 'x');
+ helpers.doKeys(';');
+ helpers.doKeys('2', ';');
+ eq(9, cm.getCursor().ch);
+}, { value: '01x3xx678x'});
+testVim('F;', function(cm, vim, helpers) {
+ cm.setCursor(0, 8);
+ helpers.doKeys('F', 'x');
+ helpers.doKeys(';');
+ helpers.doKeys('2', ';');
+ eq(2, cm.getCursor().ch);
+}, { value: '01x3xx6x8x'});
+testVim('t;', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('t', 'x');
+ helpers.doKeys(';');
+ helpers.doKeys('2', ';');
+ eq(8, cm.getCursor().ch);
+}, { value: '01x3xx678x'});
+testVim('T;', function(cm, vim, helpers) {
+ cm.setCursor(0, 9);
+ helpers.doKeys('T', 'x');
+ helpers.doKeys(';');
+ helpers.doKeys('2', ';');
+ eq(2, cm.getCursor().ch);
+}, { value: '0xx3xx678x'});
+testVim('f,', function(cm, vim, helpers) {
+ cm.setCursor(0, 6);
+ helpers.doKeys('f', 'x');
+ helpers.doKeys(',');
+ helpers.doKeys('2', ',');
+ eq(2, cm.getCursor().ch);
+}, { value: '01x3xx678x'});
+testVim('F,', function(cm, vim, helpers) {
+ cm.setCursor(0, 3);
+ helpers.doKeys('F', 'x');
+ helpers.doKeys(',');
+ helpers.doKeys('2', ',');
+ eq(9, cm.getCursor().ch);
+}, { value: '01x3xx678x'});
+testVim('t,', function(cm, vim, helpers) {
+ cm.setCursor(0, 6);
+ helpers.doKeys('t', 'x');
+ helpers.doKeys(',');
+ helpers.doKeys('2', ',');
+ eq(3, cm.getCursor().ch);
+}, { value: '01x3xx678x'});
+testVim('T,', function(cm, vim, helpers) {
+ cm.setCursor(0, 4);
+ helpers.doKeys('T', 'x');
+ helpers.doKeys(',');
+ helpers.doKeys('2', ',');
+ eq(8, cm.getCursor().ch);
+}, { value: '01x3xx67xx'});
+testVim('fd,;', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('f', '4');
+ cm.setCursor(0, 0);
+ helpers.doKeys('d', ';');
+ eq('56789', cm.getValue());
+ helpers.doKeys('u');
+ cm.setCursor(0, 9);
+ helpers.doKeys('d', ',');
+ eq('01239', cm.getValue());
+}, { value: '0123456789'});
+testVim('Fd,;', function(cm, vim, helpers) {
+ cm.setCursor(0, 9);
+ helpers.doKeys('F', '4');
+ cm.setCursor(0, 9);
+ helpers.doKeys('d', ';');
+ eq('01239', cm.getValue());
+ helpers.doKeys('u');
+ cm.setCursor(0, 0);
+ helpers.doKeys('d', ',');
+ eq('56789', cm.getValue());
+}, { value: '0123456789'});
+testVim('td,;', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('t', '4');
+ cm.setCursor(0, 0);
+ helpers.doKeys('d', ';');
+ eq('456789', cm.getValue());
+ helpers.doKeys('u');
+ cm.setCursor(0, 9);
+ helpers.doKeys('d', ',');
+ eq('012349', cm.getValue());
+}, { value: '0123456789'});
+testVim('Td,;', function(cm, vim, helpers) {
+ cm.setCursor(0, 9);
+ helpers.doKeys('T', '4');
+ cm.setCursor(0, 9);
+ helpers.doKeys('d', ';');
+ eq('012349', cm.getValue());
+ helpers.doKeys('u');
+ cm.setCursor(0, 0);
+ helpers.doKeys('d', ',');
+ eq('456789', cm.getValue());
+}, { value: '0123456789'});
+testVim('fc,;', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('f', '4');
+ cm.setCursor(0, 0);
+ helpers.doKeys('c', ';', '<Esc>');
+ eq('56789', cm.getValue());
+ helpers.doKeys('u');
+ cm.setCursor(0, 9);
+ helpers.doKeys('c', ',');
+ eq('01239', cm.getValue());
+}, { value: '0123456789'});
+testVim('Fc,;', function(cm, vim, helpers) {
+ cm.setCursor(0, 9);
+ helpers.doKeys('F', '4');
+ cm.setCursor(0, 9);
+ helpers.doKeys('c', ';', '<Esc>');
+ eq('01239', cm.getValue());
+ helpers.doKeys('u');
+ cm.setCursor(0, 0);
+ helpers.doKeys('c', ',');
+ eq('56789', cm.getValue());
+}, { value: '0123456789'});
+testVim('tc,;', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('t', '4');
+ cm.setCursor(0, 0);
+ helpers.doKeys('c', ';', '<Esc>');
+ eq('456789', cm.getValue());
+ helpers.doKeys('u');
+ cm.setCursor(0, 9);
+ helpers.doKeys('c', ',');
+ eq('012349', cm.getValue());
+}, { value: '0123456789'});
+testVim('Tc,;', function(cm, vim, helpers) {
+ cm.setCursor(0, 9);
+ helpers.doKeys('T', '4');
+ cm.setCursor(0, 9);
+ helpers.doKeys('c', ';', '<Esc>');
+ eq('012349', cm.getValue());
+ helpers.doKeys('u');
+ cm.setCursor(0, 0);
+ helpers.doKeys('c', ',');
+ eq('456789', cm.getValue());
+}, { value: '0123456789'});
+testVim('fy,;', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('f', '4');
+ cm.setCursor(0, 0);
+ helpers.doKeys('y', ';', 'P');
+ eq('012340123456789', cm.getValue());
+ helpers.doKeys('u');
+ cm.setCursor(0, 9);
+ helpers.doKeys('y', ',', 'P');
+ eq('012345678456789', cm.getValue());
+}, { value: '0123456789'});
+testVim('Fy,;', function(cm, vim, helpers) {
+ cm.setCursor(0, 9);
+ helpers.doKeys('F', '4');
+ cm.setCursor(0, 9);
+ helpers.doKeys('y', ';', 'p');
+ eq('012345678945678', cm.getValue());
+ helpers.doKeys('u');
+ cm.setCursor(0, 0);
+ helpers.doKeys('y', ',', 'P');
+ eq('012340123456789', cm.getValue());
+}, { value: '0123456789'});
+testVim('ty,;', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys('t', '4');
+ cm.setCursor(0, 0);
+ helpers.doKeys('y', ';', 'P');
+ eq('01230123456789', cm.getValue());
+ helpers.doKeys('u');
+ cm.setCursor(0, 9);
+ helpers.doKeys('y', ',', 'p');
+ eq('01234567895678', cm.getValue());
+}, { value: '0123456789'});
+testVim('Ty,;', function(cm, vim, helpers) {
+ cm.setCursor(0, 9);
+ helpers.doKeys('T', '4');
+ cm.setCursor(0, 9);
+ helpers.doKeys('y', ';', 'p');
+ eq('01234567895678', cm.getValue());
+ helpers.doKeys('u');
+ cm.setCursor(0, 0);
+ helpers.doKeys('y', ',', 'P');
+ eq('01230123456789', cm.getValue());
+}, { value: '0123456789'});
+testVim('HML', function(cm, vim, helpers) {
+ var lines = 35;
+ var textHeight = cm.defaultTextHeight();
+ cm.setSize(600, lines*textHeight);
+ cm.setCursor(120, 0);
+ helpers.doKeys('H');
+ helpers.assertCursorAt(86, 2);
+ helpers.doKeys('L');
+ helpers.assertCursorAt(120, 4);
+ helpers.doKeys('M');
+ helpers.assertCursorAt(103,4);
+}, { value: (function(){
+ var lines = new Array(100);
+ var upper = ' xx\n';
+ var lower = ' xx\n';
+ upper = lines.join(upper);
+ lower = lines.join(lower);
+ return upper + lower;
+})()});
+
+var zVals = [];
+forEach(['zb','zz','zt','z-','z.','z<CR>'], function(e, idx){
+ var lineNum = 250;
+ var lines = 35;
+ testVim(e, function(cm, vim, helpers) {
+ var k1 = e[0];
+ var k2 = e.substring(1);
+ var textHeight = cm.defaultTextHeight();
+ cm.setSize(600, lines*textHeight);
+ cm.setCursor(lineNum, 0);
+ helpers.doKeys(k1, k2);
+ zVals[idx] = cm.getScrollInfo().top;
+ }, { value: (function(){
+ return new Array(500).join('\n');
+ })()});
+});
+testVim('zb_to_bottom', function(cm, vim, helpers){
+ var lineNum = 250;
+ cm.setSize(600, 35*cm.defaultTextHeight());
+ cm.setCursor(lineNum, 0);
+ helpers.doKeys('z', 'b');
+ var scrollInfo = cm.getScrollInfo();
+ eq(scrollInfo.top + scrollInfo.clientHeight, cm.charCoords(Pos(lineNum, 0), 'local').bottom);
+}, { value: (function(){
+ return new Array(500).join('\n');
+})()});
+testVim('zt_to_top', function(cm, vim, helpers){
+ var lineNum = 250;
+ cm.setSize(600, 35*cm.defaultTextHeight());
+ cm.setCursor(lineNum, 0);
+ helpers.doKeys('z', 't');
+ eq(cm.getScrollInfo().top, cm.charCoords(Pos(lineNum, 0), 'local').top);
+}, { value: (function(){
+ return new Array(500).join('\n');
+})()});
+testVim('zb<zz', function(cm, vim, helpers){
+ eq(zVals[0]<zVals[1], true);
+});
+testVim('zz<zt', function(cm, vim, helpers){
+ eq(zVals[1]<zVals[2], true);
+});
+testVim('zb==z-', function(cm, vim, helpers){
+ eq(zVals[0], zVals[3]);
+});
+testVim('zz==z.', function(cm, vim, helpers){
+ eq(zVals[1], zVals[4]);
+});
+testVim('zt==z<CR>', function(cm, vim, helpers){
+ eq(zVals[2], zVals[5]);
+});
+
+var moveTillCharacterSandbox =
+ 'The quick brown fox \n';
+testVim('moveTillCharacter', function(cm, vim, helpers){
+ cm.setCursor(0, 0);
+ // Search for the 'q'.
+ cm.openDialog = helpers.fakeOpenDialog('q');
+ helpers.doKeys('/');
+ eq(4, cm.getCursor().ch);
+ // Jump to just before the first o in the list.
+ helpers.doKeys('t');
+ helpers.doKeys('o');
+ eq('The quick brown fox \n', cm.getValue());
+ // Delete that one character.
+ helpers.doKeys('d');
+ helpers.doKeys('t');
+ helpers.doKeys('o');
+ eq('The quick bown fox \n', cm.getValue());
+ // Delete everything until the next 'o'.
+ helpers.doKeys('.');
+ eq('The quick box \n', cm.getValue());
+ // An unmatched character should have no effect.
+ helpers.doKeys('d');
+ helpers.doKeys('t');
+ helpers.doKeys('q');
+ eq('The quick box \n', cm.getValue());
+ // Matches should only be possible on single lines.
+ helpers.doKeys('d');
+ helpers.doKeys('t');
+ helpers.doKeys('z');
+ eq('The quick box \n', cm.getValue());
+ // After all that, the search for 'q' should still be active, so the 'N' command
+ // can run it again in reverse. Use that to delete everything back to the 'q'.
+ helpers.doKeys('d');
+ helpers.doKeys('N');
+ eq('The ox \n', cm.getValue());
+ eq(4, cm.getCursor().ch);
+}, { value: moveTillCharacterSandbox});
+testVim('searchForPipe', function(cm, vim, helpers){
+ CodeMirror.Vim.setOption('pcre', false);
+ cm.setCursor(0, 0);
+ // Search for the '|'.
+ cm.openDialog = helpers.fakeOpenDialog('|');
+ helpers.doKeys('/');
+ eq(4, cm.getCursor().ch);
+}, { value: 'this|that'});
+
+
+var scrollMotionSandbox =
+ '\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n';
+testVim('scrollMotion', function(cm, vim, helpers){
+ var prevCursor, prevScrollInfo;
+ cm.setCursor(0, 0);
+ // ctrl-y at the top of the file should have no effect.
+ helpers.doKeys('<C-y>');
+ eq(0, cm.getCursor().line);
+ prevScrollInfo = cm.getScrollInfo();
+ helpers.doKeys('<C-e>');
+ eq(1, cm.getCursor().line);
+ is(prevScrollInfo.top < cm.getScrollInfo().top);
+ // Jump to the end of the sandbox.
+ cm.setCursor(1000, 0);
+ prevCursor = cm.getCursor();
+ // ctrl-e at the bottom of the file should have no effect.
+ helpers.doKeys('<C-e>');
+ eq(prevCursor.line, cm.getCursor().line);
+ prevScrollInfo = cm.getScrollInfo();
+ helpers.doKeys('<C-y>');
+ eq(prevCursor.line - 1, cm.getCursor().line, "Y");
+ is(prevScrollInfo.top > cm.getScrollInfo().top);
+}, { value: scrollMotionSandbox});
+
+var squareBracketMotionSandbox = ''+
+ '({\n'+//0
+ ' ({\n'+//11
+ ' /*comment {\n'+//2
+ ' */(\n'+//3
+ '#else \n'+//4
+ ' /* )\n'+//5
+ '#if }\n'+//6
+ ' )}*/\n'+//7
+ ')}\n'+//8
+ '{}\n'+//9
+ '#else {{\n'+//10
+ '{}\n'+//11
+ '}\n'+//12
+ '{\n'+//13
+ '#endif\n'+//14
+ '}\n'+//15
+ '}\n'+//16
+ '#else';//17
+testVim('[[, ]]', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys(']', ']');
+ helpers.assertCursorAt(9,0);
+ helpers.doKeys('2', ']', ']');
+ helpers.assertCursorAt(13,0);
+ helpers.doKeys(']', ']');
+ helpers.assertCursorAt(17,0);
+ helpers.doKeys('[', '[');
+ helpers.assertCursorAt(13,0);
+ helpers.doKeys('2', '[', '[');
+ helpers.assertCursorAt(9,0);
+ helpers.doKeys('[', '[');
+ helpers.assertCursorAt(0,0);
+}, { value: squareBracketMotionSandbox});
+testVim('[], ][', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doKeys(']', '[');
+ helpers.assertCursorAt(12,0);
+ helpers.doKeys('2', ']', '[');
+ helpers.assertCursorAt(16,0);
+ helpers.doKeys(']', '[');
+ helpers.assertCursorAt(17,0);
+ helpers.doKeys('[', ']');
+ helpers.assertCursorAt(16,0);
+ helpers.doKeys('2', '[', ']');
+ helpers.assertCursorAt(12,0);
+ helpers.doKeys('[', ']');
+ helpers.assertCursorAt(0,0);
+}, { value: squareBracketMotionSandbox});
+testVim('[{, ]}', function(cm, vim, helpers) {
+ cm.setCursor(4, 10);
+ helpers.doKeys('[', '{');
+ helpers.assertCursorAt(2,12);
+ helpers.doKeys('2', '[', '{');
+ helpers.assertCursorAt(0,1);
+ cm.setCursor(4, 10);
+ helpers.doKeys(']', '}');
+ helpers.assertCursorAt(6,11);
+ helpers.doKeys('2', ']', '}');
+ helpers.assertCursorAt(8,1);
+ cm.setCursor(0,1);
+ helpers.doKeys(']', '}');
+ helpers.assertCursorAt(8,1);
+ helpers.doKeys('[', '{');
+ helpers.assertCursorAt(0,1);
+}, { value: squareBracketMotionSandbox});
+testVim('[(, ])', function(cm, vim, helpers) {
+ cm.setCursor(4, 10);
+ helpers.doKeys('[', '(');
+ helpers.assertCursorAt(3,14);
+ helpers.doKeys('2', '[', '(');
+ helpers.assertCursorAt(0,0);
+ cm.setCursor(4, 10);
+ helpers.doKeys(']', ')');
+ helpers.assertCursorAt(5,11);
+ helpers.doKeys('2', ']', ')');
+ helpers.assertCursorAt(8,0);
+ helpers.doKeys('[', '(');
+ helpers.assertCursorAt(0,0);
+ helpers.doKeys(']', ')');
+ helpers.assertCursorAt(8,0);
+}, { value: squareBracketMotionSandbox});
+testVim('[*, ]*, [/, ]/', function(cm, vim, helpers) {
+ forEach(['*', '/'], function(key){
+ cm.setCursor(7, 0);
+ helpers.doKeys('2', '[', key);
+ helpers.assertCursorAt(2,2);
+ helpers.doKeys('2', ']', key);
+ helpers.assertCursorAt(7,5);
+ });
+}, { value: squareBracketMotionSandbox});
+testVim('[#, ]#', function(cm, vim, helpers) {
+ cm.setCursor(10, 3);
+ helpers.doKeys('2', '[', '#');
+ helpers.assertCursorAt(4,0);
+ helpers.doKeys('5', ']', '#');
+ helpers.assertCursorAt(17,0);
+ cm.setCursor(10, 3);
+ helpers.doKeys(']', '#');
+ helpers.assertCursorAt(14,0);
+}, { value: squareBracketMotionSandbox});
+testVim('[m, ]m, [M, ]M', function(cm, vim, helpers) {
+ cm.setCursor(11, 0);
+ helpers.doKeys('[', 'm');
+ helpers.assertCursorAt(10,7);
+ helpers.doKeys('4', '[', 'm');
+ helpers.assertCursorAt(1,3);
+ helpers.doKeys('5', ']', 'm');
+ helpers.assertCursorAt(11,0);
+ helpers.doKeys('[', 'M');
+ helpers.assertCursorAt(9,1);
+ helpers.doKeys('3', ']', 'M');
+ helpers.assertCursorAt(15,0);
+ helpers.doKeys('5', '[', 'M');
+ helpers.assertCursorAt(7,3);
+}, { value: squareBracketMotionSandbox});
+
+testVim('i_indent_right', function(cm, vim, helpers) {
+ cm.setCursor(0, 3);
+ var expectedValue = ' word1\nword2\nword3 ';
+ helpers.doKeys('i', '<C-t>');
+ eq(expectedValue, cm.getValue());
+ helpers.assertCursorAt(0, 5);
+}, { value: ' word1\nword2\nword3 ', indentUnit: 2 });
+testVim('i_indent_left', function(cm, vim, helpers) {
+ cm.setCursor(0, 3);
+ var expectedValue = ' word1\nword2\nword3 ';
+ helpers.doKeys('i', '<C-d>');
+ eq(expectedValue, cm.getValue());
+ helpers.assertCursorAt(0, 1);
+}, { value: ' word1\nword2\nword3 ', indentUnit: 2 });
+
+// Ex mode tests
+testVim('ex_go_to_line', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doEx('4');
+ helpers.assertCursorAt(3, 0);
+}, { value: 'a\nb\nc\nd\ne\n'});
+testVim('ex_go_to_mark', function(cm, vim, helpers) {
+ cm.setCursor(3, 0);
+ helpers.doKeys('m', 'a');
+ cm.setCursor(0, 0);
+ helpers.doEx('\'a');
+ helpers.assertCursorAt(3, 0);
+}, { value: 'a\nb\nc\nd\ne\n'});
+testVim('ex_go_to_line_offset', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doEx('+3');
+ helpers.assertCursorAt(3, 0);
+ helpers.doEx('-1');
+ helpers.assertCursorAt(2, 0);
+ helpers.doEx('.2');
+ helpers.assertCursorAt(4, 0);
+ helpers.doEx('.-3');
+ helpers.assertCursorAt(1, 0);
+}, { value: 'a\nb\nc\nd\ne\n'});
+testVim('ex_go_to_mark_offset', function(cm, vim, helpers) {
+ cm.setCursor(2, 0);
+ helpers.doKeys('m', 'a');
+ cm.setCursor(0, 0);
+ helpers.doEx('\'a1');
+ helpers.assertCursorAt(3, 0);
+ helpers.doEx('\'a-1');
+ helpers.assertCursorAt(1, 0);
+ helpers.doEx('\'a+2');
+ helpers.assertCursorAt(4, 0);
+}, { value: 'a\nb\nc\nd\ne\n'});
+testVim('ex_write', function(cm, vim, helpers) {
+ var tmp = CodeMirror.commands.save;
+ var written;
+ var actualCm;
+ CodeMirror.commands.save = function(cm) {
+ written = true;
+ actualCm = cm;
+ };
+ // Test that w, wr, wri ... write all trigger :write.
+ var command = 'write';
+ for (var i = 1; i < command.length; i++) {
+ written = false;
+ actualCm = null;
+ helpers.doEx(command.substring(0, i));
+ eq(written, true);
+ eq(actualCm, cm);
+ }
+ CodeMirror.commands.save = tmp;
+});
+testVim('ex_sort', function(cm, vim, helpers) {
+ helpers.doEx('sort');
+ eq('Z\na\nb\nc\nd', cm.getValue());
+}, { value: 'b\nZ\nd\nc\na'});
+testVim('ex_sort_reverse', function(cm, vim, helpers) {
+ helpers.doEx('sort!');
+ eq('d\nc\nb\na', cm.getValue());
+}, { value: 'b\nd\nc\na'});
+testVim('ex_sort_range', function(cm, vim, helpers) {
+ helpers.doEx('2,3sort');
+ eq('b\nc\nd\na', cm.getValue());
+}, { value: 'b\nd\nc\na'});
+testVim('ex_sort_oneline', function(cm, vim, helpers) {
+ helpers.doEx('2sort');
+ // Expect no change.
+ eq('b\nd\nc\na', cm.getValue());
+}, { value: 'b\nd\nc\na'});
+testVim('ex_sort_ignoreCase', function(cm, vim, helpers) {
+ helpers.doEx('sort i');
+ eq('a\nb\nc\nd\nZ', cm.getValue());
+}, { value: 'b\nZ\nd\nc\na'});
+testVim('ex_sort_unique', function(cm, vim, helpers) {
+ helpers.doEx('sort u');
+ eq('Z\na\nb\nc\nd', cm.getValue());
+}, { value: 'b\nZ\na\na\nd\na\nc\na'});
+testVim('ex_sort_decimal', function(cm, vim, helpers) {
+ helpers.doEx('sort d');
+ eq('d3\n s5\n6\n.9', cm.getValue());
+}, { value: '6\nd3\n s5\n.9'});
+testVim('ex_sort_decimal_negative', function(cm, vim, helpers) {
+ helpers.doEx('sort d');
+ eq('z-9\nd3\n s5\n6\n.9', cm.getValue());
+}, { value: '6\nd3\n s5\n.9\nz-9'});
+testVim('ex_sort_decimal_reverse', function(cm, vim, helpers) {
+ helpers.doEx('sort! d');
+ eq('.9\n6\n s5\nd3', cm.getValue());
+}, { value: '6\nd3\n s5\n.9'});
+testVim('ex_sort_hex', function(cm, vim, helpers) {
+ helpers.doEx('sort x');
+ eq(' s5\n6\n.9\n&0xB\nd3', cm.getValue());
+}, { value: '6\nd3\n s5\n&0xB\n.9'});
+testVim('ex_sort_octal', function(cm, vim, helpers) {
+ helpers.doEx('sort o');
+ eq('.9\n.8\nd3\n s5\n6', cm.getValue());
+}, { value: '6\nd3\n s5\n.9\n.8'});
+testVim('ex_sort_decimal_mixed', function(cm, vim, helpers) {
+ helpers.doEx('sort d');
+ eq('z\ny\nc1\nb2\na3', cm.getValue());
+}, { value: 'a3\nz\nc1\ny\nb2'});
+testVim('ex_sort_decimal_mixed_reverse', function(cm, vim, helpers) {
+ helpers.doEx('sort! d');
+ eq('a3\nb2\nc1\nz\ny', cm.getValue());
+}, { value: 'a3\nz\nc1\ny\nb2'});
+testVim('ex_sort_pattern_alpha', function(cm, vim, helpers) {
+ helpers.doEx('sort /[a-z]/');
+ eq('a3\nb2\nc1\ny\nz', cm.getValue());
+}, { value: 'z\ny\nc1\nb2\na3'});
+testVim('ex_sort_pattern_alpha_reverse', function(cm, vim, helpers) {
+ helpers.doEx('sort! /[a-z]/');
+ eq('z\ny\nc1\nb2\na3', cm.getValue());
+}, { value: 'z\ny\nc1\nb2\na3'});
+testVim('ex_sort_pattern_alpha_ignoreCase', function(cm, vim, helpers) {
+ helpers.doEx('sort i/[a-z]/');
+ eq('a3\nb2\nC1\nY\nz', cm.getValue());
+}, { value: 'z\nY\nC1\nb2\na3'});
+testVim('ex_sort_pattern_alpha_longer', function(cm, vim, helpers) {
+ helpers.doEx('sort /[a-z]+/');
+ eq('a\naa\nab\nade\nadele\nadelle\nadriana\nalex\nalexandra\nb\nc\ny\nz', cm.getValue());
+}, { value: 'z\nab\naa\nade\nadelle\nalexandra\nalex\nadriana\nadele\ny\nc\nb\na'});
+testVim('ex_sort_pattern_alpha_only', function(cm, vim, helpers) {
+ helpers.doEx('sort /^[a-z]$/');
+ eq('z1\ny2\na3\nb\nc', cm.getValue());
+}, { value: 'z1\ny2\na3\nc\nb'});
+testVim('ex_sort_pattern_alpha_only_reverse', function(cm, vim, helpers) {
+ helpers.doEx('sort! /^[a-z]$/');
+ eq('c\nb\nz1\ny2\na3', cm.getValue());
+}, { value: 'z1\ny2\na3\nc\nb'});
+testVim('ex_sort_pattern_alpha_num', function(cm, vim, helpers) {
+ helpers.doEx('sort /[a-z][0-9]/');
+ eq('c\nb\na3\ny2\nz1', cm.getValue());
+}, { value: 'z1\ny2\na3\nc\nb'});
+// test for :global command
+testVim('ex_global', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doEx('g/one/s//two');
+ eq('two two\n two two\n two two', cm.getValue());
+ helpers.doEx('1,2g/two/s//one');
+ eq('one one\n one one\n two two', cm.getValue());
+}, {value: 'one one\n one one\n one one'});
+testVim('ex_global_confirm', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ var onKeyDown;
+ var openDialogSave = cm.openDialog;
+ var KEYCODES = {
+ a: 65,
+ n: 78,
+ q: 81,
+ y: 89
+ };
+ // Intercept the ex command, 'global'
+ cm.openDialog = function(template, callback, options) {
+ // Intercept the prompt for the embedded ex command, 'substitute'
+ cm.openDialog = function(template, callback, options) {
+ onKeyDown = options.onKeyDown;
+ };
+ callback('g/one/s//two/gc');
+ };
+ helpers.doKeys(':');
+ var close = function() {};
+ onKeyDown({keyCode: KEYCODES.n}, '', close);
+ onKeyDown({keyCode: KEYCODES.y}, '', close);
+ onKeyDown({keyCode: KEYCODES.a}, '', close);
+ onKeyDown({keyCode: KEYCODES.q}, '', close);
+ onKeyDown({keyCode: KEYCODES.y}, '', close);
+ eq('one two\n two two\n one one\n two one\n one one', cm.getValue());
+}, {value: 'one one\n one one\n one one\n one one\n one one'});
+// Basic substitute tests.
+testVim('ex_substitute_same_line', function(cm, vim, helpers) {
+ cm.setCursor(1, 0);
+ helpers.doEx('s/one/two/g');
+ eq('one one\n two two', cm.getValue());
+}, { value: 'one one\n one one'});
+testVim('ex_substitute_alternate_separator', function(cm, vim, helpers) {
+ cm.setCursor(1, 0);
+ helpers.doEx('s#o/e#two#g');
+ eq('o/e o/e\n two two', cm.getValue());
+}, { value: 'o/e o/e\n o/e o/e'});
+testVim('ex_substitute_full_file', function(cm, vim, helpers) {
+ cm.setCursor(1, 0);
+ helpers.doEx('%s/one/two/g');
+ eq('two two\n two two', cm.getValue());
+}, { value: 'one one\n one one'});
+testVim('ex_substitute_input_range', function(cm, vim, helpers) {
+ cm.setCursor(1, 0);
+ helpers.doEx('1,3s/\\d/0/g');
+ eq('0\n0\n0\n4', cm.getValue());
+}, { value: '1\n2\n3\n4' });
+testVim('ex_substitute_range_current_to_input', function(cm, vim, helpers) {
+ cm.setCursor(1, 0);
+ helpers.doEx('.,3s/\\d/0/g');
+ eq('1\n0\n0\n4', cm.getValue());
+}, { value: '1\n2\n3\n4' });
+testVim('ex_substitute_range_input_to_current', function(cm, vim, helpers) {
+ cm.setCursor(3, 0);
+ helpers.doEx('2,.s/\\d/0/g');
+ eq('1\n0\n0\n0\n5', cm.getValue());
+}, { value: '1\n2\n3\n4\n5' });
+testVim('ex_substitute_range_offset', function(cm, vim, helpers) {
+ cm.setCursor(2, 0);
+ helpers.doEx('-1,+1s/\\d/0/g');
+ eq('1\n0\n0\n0\n5', cm.getValue());
+}, { value: '1\n2\n3\n4\n5' });
+testVim('ex_substitute_range_implicit_offset', function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ helpers.doEx('.1,.3s/\\d/0/g');
+ eq('1\n0\n0\n0\n5', cm.getValue());
+}, { value: '1\n2\n3\n4\n5' });
+testVim('ex_substitute_to_eof', function(cm, vim, helpers) {
+ cm.setCursor(2, 0);
+ helpers.doEx('.,$s/\\d/0/g');
+ eq('1\n2\n0\n0\n0', cm.getValue());
+}, { value: '1\n2\n3\n4\n5' });
+testVim('ex_substitute_to_relative_eof', function(cm, vim, helpers) {
+ cm.setCursor(4, 0);
+ helpers.doEx('2,$-2s/\\d/0/g');
+ eq('1\n0\n0\n4\n5', cm.getValue());
+}, { value: '1\n2\n3\n4\n5' });
+testVim('ex_substitute_range_mark', function(cm, vim, helpers) {
+ cm.setCursor(2, 0);
+ helpers.doKeys('ma');
+ cm.setCursor(0, 0);
+ helpers.doEx('.,\'as/\\d/0/g');
+ eq('0\n0\n0\n4\n5', cm.getValue());
+}, { value: '1\n2\n3\n4\n5' });
+testVim('ex_substitute_range_mark_offset', function(cm, vim, helpers) {
+ cm.setCursor(2, 0);
+ helpers.doKeys('ma');
+ cm.setCursor(0, 0);
+ helpers.doEx('\'a-1,\'a+1s/\\d/0/g');
+ eq('1\n0\n0\n0\n5', cm.getValue());
+}, { value: '1\n2\n3\n4\n5' });
+testVim('ex_substitute_visual_range', function(cm, vim, helpers) {
+ cm.setCursor(1, 0);
+ // Set last visual mode selection marks '< and '> at lines 2 and 4
+ helpers.doKeys('V', '2', 'j', 'v');
+ helpers.doEx('\'<,\'>s/\\d/0/g');
+ eq('1\n0\n0\n0\n5', cm.getValue());
+}, { value: '1\n2\n3\n4\n5' });
+testVim('ex_substitute_empty_query', function(cm, vim, helpers) {
+ // If the query is empty, use last query.
+ cm.setCursor(1, 0);
+ cm.openDialog = helpers.fakeOpenDialog('1');
+ helpers.doKeys('/');
+ helpers.doEx('s//b/g');
+ eq('abb ab2 ab3', cm.getValue());
+}, { value: 'a11 a12 a13' });
+testVim('ex_substitute_javascript', function(cm, vim, helpers) {
+ CodeMirror.Vim.setOption('pcre', false);
+ cm.setCursor(1, 0);
+ // Throw all the things that javascript likes to treat as special values
+ // into the replace part. All should be literal (this is VIM).
+ helpers.doEx('s/\\(\\d+\\)/$$ $\' $` $& \\1/g')
+ eq('a $$ $\' $` $& 0 b', cm.getValue());
+}, { value: 'a 0 b' });
+testVim('ex_substitute_empty_arguments', function(cm,vim,helpers) {
+ cm.setCursor(0, 0);
+ helpers.doEx('s/a/b/g');
+ cm.setCursor(1, 0);
+ helpers.doEx('s');
+ eq('b b\nb a', cm.getValue());
+}, {value: 'a a\na a'});
+
+// More complex substitute tests that test both pcre and nopcre options.
+function testSubstitute(name, options) {
+ testVim(name + '_pcre', function(cm, vim, helpers) {
+ cm.setCursor(1, 0);
+ CodeMirror.Vim.setOption('pcre', true);
+ helpers.doEx(options.expr);
+ eq(options.expectedValue, cm.getValue());
+ }, options);
+ // If no noPcreExpr is defined, assume that it's the same as the expr.
+ var noPcreExpr = options.noPcreExpr ? options.noPcreExpr : options.expr;
+ testVim(name + '_nopcre', function(cm, vim, helpers) {
+ cm.setCursor(1, 0);
+ CodeMirror.Vim.setOption('pcre', false);
+ helpers.doEx(noPcreExpr);
+ eq(options.expectedValue, cm.getValue());
+ }, options);
+}
+testSubstitute('ex_substitute_capture', {
+ value: 'a11 a12 a13',
+ expectedValue: 'a1111 a1212 a1313',
+ // $n is a backreference
+ expr: 's/(\\d+)/$1$1/g',
+ // \n is a backreference.
+ noPcreExpr: 's/\\(\\d+\\)/\\1\\1/g'});
+testSubstitute('ex_substitute_capture2', {
+ value: 'a 0 b',
+ expectedValue: 'a $00 b',
+ expr: 's/(\\d+)/$$$1$1/g',
+ noPcreExpr: 's/\\(\\d+\\)/$\\1\\1/g'});
+testSubstitute('ex_substitute_nocapture', {
+ value: 'a11 a12 a13',
+ expectedValue: 'a$1$1 a$1$1 a$1$1',
+ expr: 's/(\\d+)/$$1$$1/g',
+ noPcreExpr: 's/\\(\\d+\\)/$1$1/g'});
+testSubstitute('ex_substitute_nocapture2', {
+ value: 'a 0 b',
+ expectedValue: 'a $10 b',
+ expr: 's/(\\d+)/$$1$1/g',
+ noPcreExpr: 's/\\(\\d+\\)/\\$1\\1/g'});
+testSubstitute('ex_substitute_nocapture', {
+ value: 'a b c',
+ expectedValue: 'a $ c',
+ expr: 's/b/$$/',
+ noPcreExpr: 's/b/$/'});
+testSubstitute('ex_substitute_slash_regex', {
+ value: 'one/two \n three/four',
+ expectedValue: 'one|two \n three|four',
+ expr: '%s/\\//|'});
+testSubstitute('ex_substitute_pipe_regex', {
+ value: 'one|two \n three|four',
+ expectedValue: 'one,two \n three,four',
+ expr: '%s/\\|/,/',
+ noPcreExpr: '%s/|/,/'});
+testSubstitute('ex_substitute_or_regex', {
+ value: 'one|two \n three|four',
+ expectedValue: 'ana|twa \n thraa|faar',
+ expr: '%s/o|e|u/a/g',
+ noPcreExpr: '%s/o\\|e\\|u/a/g'});
+testSubstitute('ex_substitute_or_word_regex', {
+ value: 'one|two \n three|four',
+ expectedValue: 'five|five \n three|four',
+ expr: '%s/(one|two)/five/g',
+ noPcreExpr: '%s/\\(one\\|two\\)/five/g'});
+testSubstitute('ex_substitute_forward_slash_regex', {
+ value: 'forward slash \/ was here',
+ expectedValue: 'forward slash was here',
+ expr: '%s#\\/##g',
+ noPcreExpr: '%s#/##g'});
+testVim("ex_substitute_ampersand_pcre", function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ CodeMirror.Vim.setOption('pcre', true);
+ helpers.doEx('%s/foo/namespace.&/');
+ eq("namespace.foo", cm.getValue());
+ }, { value: 'foo' });
+testVim("ex_substitute_ampersand_multiple_pcre", function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ CodeMirror.Vim.setOption('pcre', true);
+ helpers.doEx('%s/f.o/namespace.&/');
+ eq("namespace.foo\nnamespace.fzo", cm.getValue());
+ }, { value: 'foo\nfzo' });
+testVim("ex_escaped_ampersand_should_not_substitute_pcre", function(cm, vim, helpers) {
+ cm.setCursor(0, 0);
+ CodeMirror.Vim.setOption('pcre', true);
+ helpers.doEx('%s/foo/namespace.\\&/');
+ eq("namespace.&", cm.getValue());
+ }, { value: 'foo' });
+testSubstitute('ex_substitute_backslashslash_regex', {
+ value: 'one\\two \n three\\four',
+ expectedValue: 'one,two \n three,four',
+ expr: '%s/\\\\/,'});
+testSubstitute('ex_substitute_slash_replacement', {
+ value: 'one,two \n three,four',
+ expectedValue: 'one/two \n three/four',
+ expr: '%s/,/\\/'});
+testSubstitute('ex_substitute_backslash_replacement', {
+ value: 'one,two \n three,four',
+ expectedValue: 'one\\two \n three\\four',
+ expr: '%s/,/\\\\/g'});
+testSubstitute('ex_substitute_multibackslash_replacement', {
+ value: 'one,two \n three,four',
+ expectedValue: 'one\\\\\\\\two \n three\\\\\\\\four', // 2*8 backslashes.
+ expr: '%s/,/\\\\\\\\\\\\\\\\/g'}); // 16 backslashes.
+testSubstitute('ex_substitute_dollar_match', {
+ value: 'one,two \n three,four',
+ expectedValue: 'one,two ,\n three,four',
+ expr: '%s/$/,/g'});
+testSubstitute('ex_substitute_newline_match', {
+ value: 'one,two \n three,four',
+ expectedValue: 'one,two , three,four',
+ expr: '%s/\\n/,/g'});
+testSubstitute('ex_substitute_newline_replacement', {
+ value: 'one,two \n three,four',
+ expectedValue: 'one\ntwo \n three\nfour',
+ expr: '%s/,/\\n/g'});
+testSubstitute('ex_substitute_braces_word', {
+ value: 'ababab abb ab{2}',
+ expectedValue: 'ab abb ab{2}',
+ expr: '%s/(ab){2}//g',
+ noPcreExpr: '%s/\\(ab\\)\\{2\\}//g'});
+testSubstitute('ex_substitute_braces_range', {
+ value: 'a aa aaa aaaa',
+ expectedValue: 'a a',
+ expr: '%s/a{2,3}//g',
+ noPcreExpr: '%s/a\\{2,3\\}//g'});
+testSubstitute('ex_substitute_braces_literal', {
+ value: 'ababab abb ab{2}',
+ expectedValue: 'ababab abb ',
+ expr: '%s/ab\\{2\\}//g',
+ noPcreExpr: '%s/ab{2}//g'});
+testSubstitute('ex_substitute_braces_char', {
+ value: 'ababab abb ab{2}',
+ expectedValue: 'ababab ab{2}',
+ expr: '%s/ab{2}//g',
+ noPcreExpr: '%s/ab\\{2\\}//g'});
+testSubstitute('ex_substitute_braces_no_escape', {
+ value: 'ababab abb ab{2}',
+ expectedValue: 'ababab ab{2}',
+ expr: '%s/ab{2}//g',
+ noPcreExpr: '%s/ab\\{2}//g'});
+testSubstitute('ex_substitute_count', {
+ value: '1\n2\n3\n4',
+ expectedValue: '1\n0\n0\n4',
+ expr: 's/\\d/0/i 2'});
+testSubstitute('ex_substitute_count_with_range', {
+ value: '1\n2\n3\n4',
+ expectedValue: '1\n2\n0\n0',
+ expr: '1,3s/\\d/0/ 3'});
+testSubstitute('ex_substitute_not_global', {
+ value: 'aaa\nbaa\ncaa',
+ expectedValue: 'xaa\nbxa\ncxa',
+ expr: '%s/a/x/'});
+function testSubstituteConfirm(name, command, initialValue, expectedValue, keys, finalPos) {
+ testVim(name, function(cm, vim, helpers) {
+ var savedOpenDialog = cm.openDialog;
+ var savedKeyName = CodeMirror.keyName;
+ var onKeyDown;
+ var recordedCallback;
+ var closed = true; // Start out closed, set false on second openDialog.
+ function close() {
+ closed = true;
+ }
+ // First openDialog should save callback.
+ cm.openDialog = function(template, callback, options) {
+ recordedCallback = callback;
+ }
+ // Do first openDialog.
+ helpers.doKeys(':');
+ // Second openDialog should save keyDown handler.
+ cm.openDialog = function(template, callback, options) {
+ onKeyDown = options.onKeyDown;
+ closed = false;
+ };
+ // Return the command to Vim and trigger second openDialog.
+ recordedCallback(command);
+ // The event should really use keyCode, but here just mock it out and use
+ // key and replace keyName to just return key.
+ CodeMirror.keyName = function (e) { return e.key; }
+ keys = keys.toUpperCase();
+ for (var i = 0; i < keys.length; i++) {
+ is(!closed);
+ onKeyDown({ key: keys.charAt(i) }, '', close);
+ }
+ try {
+ eq(expectedValue, cm.getValue());
+ helpers.assertCursorAt(finalPos);
+ is(closed);
+ } catch(e) {
+ throw e
+ } finally {
+ // Restore overridden functions.
+ CodeMirror.keyName = savedKeyName;
+ cm.openDialog = savedOpenDialog;
+ }
+ }, { value: initialValue });
+}
+testSubstituteConfirm('ex_substitute_confirm_emptydoc',
+ '%s/x/b/c', '', '', '', makeCursor(0, 0));
+testSubstituteConfirm('ex_substitute_confirm_nomatch',
+ '%s/x/b/c', 'ba a\nbab', 'ba a\nbab', '', makeCursor(0, 0));
+testSubstituteConfirm('ex_substitute_confirm_accept',
+ '%s/a/b/cg', 'ba a\nbab', 'bb b\nbbb', 'yyy', makeCursor(1, 1));
+testSubstituteConfirm('ex_substitute_confirm_random_keys',
+ '%s/a/b/cg', 'ba a\nbab', 'bb b\nbbb', 'ysdkywerty', makeCursor(1, 1));
+testSubstituteConfirm('ex_substitute_confirm_some',
+ '%s/a/b/cg', 'ba a\nbab', 'bb a\nbbb', 'yny', makeCursor(1, 1));
+testSubstituteConfirm('ex_substitute_confirm_all',
+ '%s/a/b/cg', 'ba a\nbab', 'bb b\nbbb', 'a', makeCursor(1, 1));
+testSubstituteConfirm('ex_substitute_confirm_accept_then_all',
+ '%s/a/b/cg', 'ba a\nbab', 'bb b\nbbb', 'ya', makeCursor(1, 1));
+testSubstituteConfirm('ex_substitute_confirm_quit',
+ '%s/a/b/cg', 'ba a\nbab', 'bb a\nbab', 'yq', makeCursor(0, 3));
+testSubstituteConfirm('ex_substitute_confirm_last',
+ '%s/a/b/cg', 'ba a\nbab', 'bb b\nbab', 'yl', makeCursor(0, 3));
+testSubstituteConfirm('ex_substitute_confirm_oneline',
+ '1s/a/b/cg', 'ba a\nbab', 'bb b\nbab', 'yl', makeCursor(0, 3));
+testSubstituteConfirm('ex_substitute_confirm_range_accept',
+ '1,2s/a/b/cg', 'aa\na \na\na', 'bb\nb \na\na', 'yyy', makeCursor(1, 0));
+testSubstituteConfirm('ex_substitute_confirm_range_some',
+ '1,3s/a/b/cg', 'aa\na \na\na', 'ba\nb \nb\na', 'ynyy', makeCursor(2, 0));
+testSubstituteConfirm('ex_substitute_confirm_range_all',
+ '1,3s/a/b/cg', 'aa\na \na\na', 'bb\nb \nb\na', 'a', makeCursor(2, 0));
+testSubstituteConfirm('ex_substitute_confirm_range_last',
+ '1,3s/a/b/cg', 'aa\na \na\na', 'bb\nb \na\na', 'yyl', makeCursor(1, 0));
+//:noh should clear highlighting of search-results but allow to resume search through n
+testVim('ex_noh_clearSearchHighlight', function(cm, vim, helpers) {
+ cm.openDialog = helpers.fakeOpenDialog('match');
+ helpers.doKeys('?');
+ helpers.doEx('noh');
+ eq(vim.searchState_.getOverlay(),null,'match-highlighting wasn\'t cleared');
+ helpers.doKeys('n');
+ helpers.assertCursorAt(0, 11,'can\'t resume search after clearing highlighting');
+}, { value: 'match nope match \n nope Match' });
+testVim('ex_yank', function (cm, vim, helpers) {
+ var curStart = makeCursor(3, 0);
+ cm.setCursor(curStart);
+ helpers.doEx('y');
+ var register = helpers.getRegisterController().getRegister();
+ var line = cm.getLine(3);
+ eq(line + '\n', register.toString());
+});
+testVim('set_boolean', function(cm, vim, helpers) {
+ CodeMirror.Vim.defineOption('testoption', true, 'boolean');
+ // Test default value is set.
+ is(CodeMirror.Vim.getOption('testoption'));
+ // Test fail to set to non-boolean
+ var result = CodeMirror.Vim.setOption('testoption', '5');
+ is(result instanceof Error);
+ // Test setOption
+ CodeMirror.Vim.setOption('testoption', false);
+ is(!CodeMirror.Vim.getOption('testoption'));
+});
+testVim('ex_set_boolean', function(cm, vim, helpers) {
+ CodeMirror.Vim.defineOption('testoption', true, 'boolean');
+ // Test default value is set.
+ is(CodeMirror.Vim.getOption('testoption'));
+ is(!cm.state.currentNotificationClose);
+ // Test fail to set to non-boolean
+ helpers.doEx('set testoption=22');
+ is(cm.state.currentNotificationClose);
+ // Test setOption
+ helpers.doEx('set notestoption');
+ is(!CodeMirror.Vim.getOption('testoption'));
+});
+testVim('set_string', function(cm, vim, helpers) {
+ CodeMirror.Vim.defineOption('testoption', 'a', 'string');
+ // Test default value is set.
+ eq('a', CodeMirror.Vim.getOption('testoption'));
+ // Test no fail to set non-string.
+ var result = CodeMirror.Vim.setOption('testoption', true);
+ is(!result);
+ // Test fail to set 'notestoption'
+ result = CodeMirror.Vim.setOption('notestoption', 'b');
+ is(result instanceof Error);
+ // Test setOption
+ CodeMirror.Vim.setOption('testoption', 'c');
+ eq('c', CodeMirror.Vim.getOption('testoption'));
+});
+testVim('ex_set_string', function(cm, vim, helpers) {
+ CodeMirror.Vim.defineOption('testopt', 'a', 'string');
+ // Test default value is set.
+ eq('a', CodeMirror.Vim.getOption('testopt'));
+ // Test fail to set 'notestopt'
+ is(!cm.state.currentNotificationClose);
+ helpers.doEx('set notestopt=b');
+ is(cm.state.currentNotificationClose);
+ // Test setOption
+ helpers.doEx('set testopt=c')
+ eq('c', CodeMirror.Vim.getOption('testopt'));
+ helpers.doEx('set testopt=c')
+ eq('c', CodeMirror.Vim.getOption('testopt', cm)); //local || global
+ eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'})); // local
+ eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'})); // global
+ eq('c', CodeMirror.Vim.getOption('testopt')); // global
+ // Test setOption global
+ helpers.doEx('setg testopt=d')
+ eq('c', CodeMirror.Vim.getOption('testopt', cm));
+ eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'}));
+ eq('d', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'}));
+ eq('d', CodeMirror.Vim.getOption('testopt'));
+ // Test setOption local
+ helpers.doEx('setl testopt=e')
+ eq('e', CodeMirror.Vim.getOption('testopt', cm));
+ eq('e', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'}));
+ eq('d', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'}));
+ eq('d', CodeMirror.Vim.getOption('testopt'));
+});
+testVim('ex_set_callback', function(cm, vim, helpers) {
+ var global;
+
+ function cb(val, cm, cfg) {
+ if (val === undefined) {
+ // Getter
+ if (cm) {
+ return cm._local;
+ } else {
+ return global;
+ }
+ } else {
+ // Setter
+ if (cm) {
+ cm._local = val;
+ } else {
+ global = val;
+ }
+ }
+ }
+
+ CodeMirror.Vim.defineOption('testopt', 'a', 'string', cb);
+ // Test default value is set.
+ eq('a', CodeMirror.Vim.getOption('testopt'));
+ // Test fail to set 'notestopt'
+ is(!cm.state.currentNotificationClose);
+ helpers.doEx('set notestopt=b');
+ is(cm.state.currentNotificationClose);
+ // Test setOption (Identical to the string tests, but via callback instead)
+ helpers.doEx('set testopt=c')
+ eq('c', CodeMirror.Vim.getOption('testopt', cm)); //local || global
+ eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'})); // local
+ eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'})); // global
+ eq('c', CodeMirror.Vim.getOption('testopt')); // global
+ // Test setOption global
+ helpers.doEx('setg testopt=d')
+ eq('c', CodeMirror.Vim.getOption('testopt', cm));
+ eq('c', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'}));
+ eq('d', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'}));
+ eq('d', CodeMirror.Vim.getOption('testopt'));
+ // Test setOption local
+ helpers.doEx('setl testopt=e')
+ eq('e', CodeMirror.Vim.getOption('testopt', cm));
+ eq('e', CodeMirror.Vim.getOption('testopt', cm, {scope: 'local'}));
+ eq('d', CodeMirror.Vim.getOption('testopt', cm, {scope: 'global'}));
+ eq('d', CodeMirror.Vim.getOption('testopt'));
+})
+testVim('ex_set_filetype', function(cm, vim, helpers) {
+ CodeMirror.defineMode('test_mode', function() {
+ return {token: function(stream) {
+ stream.match(/^\s+|^\S+/);
+ }};
+ });
+ CodeMirror.defineMode('test_mode_2', function() {
+ return {token: function(stream) {
+ stream.match(/^\s+|^\S+/);
+ }};
+ });
+ // Test mode is set.
+ helpers.doEx('set filetype=test_mode');
+ eq('test_mode', cm.getMode().name);
+ // Test 'ft' alias also sets mode.
+ helpers.doEx('set ft=test_mode_2');
+ eq('test_mode_2', cm.getMode().name);
+});
+testVim('ex_set_filetype_null', function(cm, vim, helpers) {
+ CodeMirror.defineMode('test_mode', function() {
+ return {token: function(stream) {
+ stream.match(/^\s+|^\S+/);
+ }};
+ });
+ cm.setOption('mode', 'test_mode');
+ // Test mode is set to null.
+ helpers.doEx('set filetype=');
+ eq('null', cm.getMode().name);
+});
+
+testVim('mapclear', function(cm, vim, helpers) {
+ CodeMirror.Vim.map('w', 'l');
+ cm.setCursor(0, 0);
+ helpers.assertCursorAt(0, 0);
+ helpers.doKeys('w');
+ helpers.assertCursorAt(0, 1);
+ CodeMirror.Vim.mapclear('visual');
+ helpers.doKeys('v', 'w', 'v');
+ helpers.assertCursorAt(0, 4);
+ helpers.doKeys('w');
+ helpers.assertCursorAt(0, 5);
+ CodeMirror.Vim.mapclear();
+}, { value: 'abc abc' });
+testVim('mapclear_context', function(cm, vim, helpers) {
+ CodeMirror.Vim.map('w', 'l', 'normal');
+ cm.setCursor(0, 0);
+ helpers.assertCursorAt(0, 0);
+ helpers.doKeys('w');
+ helpers.assertCursorAt(0, 1);
+ CodeMirror.Vim.mapclear('normal');
+ helpers.doKeys('w');
+ helpers.assertCursorAt(0, 4);
+ CodeMirror.Vim.mapclear();
+}, { value: 'abc abc' });
+
+testVim('ex_map_key2key', function(cm, vim, helpers) {
+ helpers.doEx('map a x');
+ helpers.doKeys('a');
+ helpers.assertCursorAt(0, 0);
+ eq('bc', cm.getValue());
+ CodeMirror.Vim.mapclear();
+}, { value: 'abc' });
+testVim('ex_unmap_key2key', function(cm, vim, helpers) {
+ helpers.doEx('map a x');
+ helpers.doEx('unmap a');
+ helpers.doKeys('a');
+ eq('vim-insert', cm.getOption('keyMap'));
+ CodeMirror.Vim.mapclear();
+}, { value: 'abc' });
+testVim('ex_unmap_key2key_does_not_remove_default', function(cm, vim, helpers) {
+ expectFail(function() {
+ helpers.doEx('unmap a');
+ });
+ helpers.doKeys('a');
+ eq('vim-insert', cm.getOption('keyMap'));
+ CodeMirror.Vim.mapclear();
+}, { value: 'abc' });
+testVim('ex_map_key2key_to_colon', function(cm, vim, helpers) {
+ helpers.doEx('map ; :');
+ var dialogOpened = false;
+ cm.openDialog = function() {
+ dialogOpened = true;
+ }
+ helpers.doKeys(';');
+ eq(dialogOpened, true);
+ CodeMirror.Vim.mapclear();
+});
+testVim('ex_map_ex2key:', function(cm, vim, helpers) {
+ helpers.doEx('map :del x');
+ helpers.doEx('del');
+ helpers.assertCursorAt(0, 0);
+ eq('bc', cm.getValue());
+ CodeMirror.Vim.mapclear();
+}, { value: 'abc' });
+testVim('ex_map_ex2ex', function(cm, vim, helpers) {
+ helpers.doEx('map :del :w');
+ var tmp = CodeMirror.commands.save;
+ var written = false;
+ var actualCm;
+ CodeMirror.commands.save = function(cm) {
+ written = true;
+ actualCm = cm;
+ };
+ helpers.doEx('del');
+ CodeMirror.commands.save = tmp;
+ eq(written, true);
+ eq(actualCm, cm);
+ CodeMirror.Vim.mapclear();
+});
+testVim('ex_map_key2ex', function(cm, vim, helpers) {
+ helpers.doEx('map a :w');
+ var tmp = CodeMirror.commands.save;
+ var written = false;
+ var actualCm;
+ CodeMirror.commands.save = function(cm) {
+ written = true;
+ actualCm = cm;
+ };
+ helpers.doKeys('a');
+ CodeMirror.commands.save = tmp;
+ eq(written, true);
+ eq(actualCm, cm);
+ CodeMirror.Vim.mapclear();
+});
+testVim('ex_map_key2key_visual_api', function(cm, vim, helpers) {
+ CodeMirror.Vim.map('b', ':w', 'visual');
+ var tmp = CodeMirror.commands.save;
+ var written = false;
+ var actualCm;
+ CodeMirror.commands.save = function(cm) {
+ written = true;
+ actualCm = cm;
+ };
+ // Mapping should not work in normal mode.
+ helpers.doKeys('b');
+ eq(written, false);
+ // Mapping should work in visual mode.
+ helpers.doKeys('v', 'b');
+ eq(written, true);
+ eq(actualCm, cm);
+
+ CodeMirror.commands.save = tmp;
+ CodeMirror.Vim.mapclear();
+});
+testVim('ex_imap', function(cm, vim, helpers) {
+ CodeMirror.Vim.map('jk', '<Esc>', 'insert');
+ helpers.doKeys('i');
+ is(vim.insertMode);
+ helpers.doKeys('j', 'k');
+ is(!vim.insertMode);
+ cm.setCursor(0, 1);
+ CodeMirror.Vim.map('jj', '<Esc>', 'insert');
+ helpers.doKeys('<C-v>', '2', 'j', 'l', 'c');
+ helpers.doKeys('f', 'o');
+ eq('1fo4\n5fo8\nafodefg', cm.getValue());
+ helpers.doKeys('j', 'j');
+ cm.setCursor(0, 0);
+ helpers.doKeys('.');
+ eq('foo4\nfoo8\nfoodefg', cm.getValue());
+ CodeMirror.Vim.mapclear();
+}, { value: '1234\n5678\nabcdefg' });
+testVim('ex_unmap_api', function(cm, vim, helpers) {
+ CodeMirror.Vim.map('<Alt-X>', 'gg', 'normal');
+ is(CodeMirror.Vim.handleKey(cm, "<Alt-X>", "normal"), "Alt-X key is mapped");
+ CodeMirror.Vim.unmap("<Alt-X>", "normal");
+ is(!CodeMirror.Vim.handleKey(cm, "<Alt-X>", "normal"), "Alt-X key is unmapped");
+ CodeMirror.Vim.mapclear();
+});
+// Testing registration of functions as ex-commands and mapping to <Key>-keys
+testVim('ex_api_test', function(cm, vim, helpers) {
+ var res=false;
+ var val='from';
+ CodeMirror.Vim.defineEx('extest','ext',function(cm,params){
+ if(params.args)val=params.args[0];
+ else res=true;
+ });
+ helpers.doEx(':ext to');
+ eq(val,'to','Defining ex-command failed');
+ CodeMirror.Vim.map('<C-CR><Space>',':ext');
+ helpers.doKeys('<C-CR>','<Space>');
+ is(res,'Mapping to key failed');
+ CodeMirror.Vim.mapclear();
+});
+// For now, this test needs to be last because it messes up : for future tests.
+testVim('ex_map_key2key_from_colon', function(cm, vim, helpers) {
+ helpers.doEx('map : x');
+ helpers.doKeys(':');
+ helpers.assertCursorAt(0, 0);
+ eq('bc', cm.getValue());
+ CodeMirror.Vim.mapclear();
+}, { value: 'abc' });
+
+testVim('noremap', function(cm, vim, helpers) {
+ CodeMirror.Vim.noremap(';', 'l');
+ cm.setCursor(0, 0);
+ eq('wOrd1', cm.getValue());
+ // Mapping should work in normal mode.
+ helpers.doKeys(';', 'r', '1');
+ eq('w1rd1', cm.getValue());
+ // Mapping will not work in insert mode because of no current fallback
+ // keyToKey mapping support.
+ helpers.doKeys('i', ';', '<Esc>');
+ eq('w;1rd1', cm.getValue());
+ // unmap all mappings
+ CodeMirror.Vim.mapclear();
+}, { value: 'wOrd1' });
+testVim('noremap_swap', function(cm, vim, helpers) {
+ CodeMirror.Vim.noremap('i', 'a', 'normal');
+ CodeMirror.Vim.noremap('a', 'i', 'normal');
+ cm.setCursor(0, 0);
+ // 'a' should act like 'i'.
+ helpers.doKeys('a');
+ eqCursorPos(Pos(0, 0), cm.getCursor());
+ // ...and 'i' should act like 'a'.
+ helpers.doKeys('<Esc>', 'i');
+ eqCursorPos(Pos(0, 1), cm.getCursor());
+ // unmap all mappings
+ CodeMirror.Vim.mapclear();
+}, { value: 'foo' });
+testVim('noremap_map_interaction', function(cm, vim, helpers) {
+ // noremap should clobber map
+ CodeMirror.Vim.map(';', 'l');
+ CodeMirror.Vim.noremap(';', 'l');
+ CodeMirror.Vim.map('l', 'j');
+ cm.setCursor(0, 0);
+ helpers.doKeys(';');
+ eqCursorPos(Pos(0, 1), cm.getCursor());
+ helpers.doKeys('l');
+ eqCursorPos(Pos(1, 1), cm.getCursor());
+ // map should be able to point to a noremap
+ CodeMirror.Vim.map('m', ';');
+ helpers.doKeys('m');
+ eqCursorPos(Pos(1, 2), cm.getCursor());
+ // unmap all mappings
+ CodeMirror.Vim.mapclear();
+}, { value: 'wOrd1\nwOrd2' });
+testVim('noremap_map_interaction2', function(cm, vim, helpers) {
+ // map should point to the most recent noremap
+ CodeMirror.Vim.noremap(';', 'l');
+ CodeMirror.Vim.map('m', ';');
+ CodeMirror.Vim.noremap(';', 'h');
+ cm.setCursor(0, 0);
+ helpers.doKeys('l');
+ eqCursorPos(Pos(0, 1), cm.getCursor());
+ helpers.doKeys('m');
+ eqCursorPos(Pos(0, 0), cm.getCursor());
+ // unmap all mappings
+ CodeMirror.Vim.mapclear();
+}, { value: 'wOrd1\nwOrd2' });
+
+// Test event handlers
+testVim('beforeSelectionChange', function(cm, vim, helpers) {
+ cm.setCursor(0, 100);
+ eqCursorPos(cm.getCursor('head'), cm.getCursor('anchor'));
+}, { value: 'abc' });
+
+testVim('increment_binary', function(cm, vim, helpers) {
+ cm.setCursor(0, 4);
+ helpers.doKeys('<C-a>');
+ eq('0b001', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('0b010', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('0b001', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('0b000', cm.getValue());
+ cm.setCursor(0, 0);
+ helpers.doKeys('<C-a>');
+ eq('0b001', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('0b010', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('0b001', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('0b000', cm.getValue());
+}, { value: '0b000' });
+
+testVim('increment_octal', function(cm, vim, helpers) {
+ cm.setCursor(0, 2);
+ helpers.doKeys('<C-a>');
+ eq('001', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('002', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('003', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('004', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('005', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('006', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('007', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('010', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('007', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('006', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('005', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('004', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('003', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('002', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('001', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('000', cm.getValue());
+ cm.setCursor(0, 0);
+ helpers.doKeys('<C-a>');
+ eq('001', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('002', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('001', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('000', cm.getValue());
+}, { value: '000' });
+
+testVim('increment_decimal', function(cm, vim, helpers) {
+ cm.setCursor(0, 2);
+ helpers.doKeys('<C-a>');
+ eq('101', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('102', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('103', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('104', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('105', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('106', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('107', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('108', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('109', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('110', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('109', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('108', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('107', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('106', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('105', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('104', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('103', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('102', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('101', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('100', cm.getValue());
+ cm.setCursor(0, 0);
+ helpers.doKeys('<C-a>');
+ eq('101', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('102', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('101', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('100', cm.getValue());
+}, { value: '100' });
+
+testVim('increment_decimal_single_zero', function(cm, vim, helpers) {
+ helpers.doKeys('<C-a>');
+ eq('1', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('2', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('3', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('4', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('5', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('6', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('7', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('8', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('9', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('10', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('9', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('8', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('7', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('6', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('5', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('4', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('3', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('2', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('1', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('0', cm.getValue());
+ cm.setCursor(0, 0);
+ helpers.doKeys('<C-a>');
+ eq('1', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('2', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('1', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('0', cm.getValue());
+}, { value: '0' });
+
+testVim('increment_hexadecimal', function(cm, vim, helpers) {
+ cm.setCursor(0, 2);
+ helpers.doKeys('<C-a>');
+ eq('0x1', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('0x2', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('0x3', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('0x4', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('0x5', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('0x6', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('0x7', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('0x8', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('0x9', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('0xa', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('0xb', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('0xc', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('0xd', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('0xe', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('0xf', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('0x10', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('0x0f', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('0x0e', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('0x0d', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('0x0c', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('0x0b', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('0x0a', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('0x09', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('0x08', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('0x07', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('0x06', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('0x05', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('0x04', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('0x03', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('0x02', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('0x01', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('0x00', cm.getValue());
+ cm.setCursor(0, 0);
+ helpers.doKeys('<C-a>');
+ eq('0x01', cm.getValue());
+ helpers.doKeys('<C-a>');
+ eq('0x02', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('0x01', cm.getValue());
+ helpers.doKeys('<C-x>');
+ eq('0x00', cm.getValue());
+}, { value: '0x0' });
diff --git a/devtools/client/shared/sourceeditor/test/codemirror/vimemacs.html b/devtools/client/shared/sourceeditor/test/codemirror/vimemacs.html
new file mode 100644
index 0000000000..5d56b57b11
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/codemirror/vimemacs.html
@@ -0,0 +1,215 @@
+<!doctype html>
+<html>
+ <head>
+ <meta charset="utf-8">
+ <title>CodeMirror: VIM/Emacs tests</title>
+ <link rel="stylesheet" href="chrome://devtools/content/shared/sourceeditor/codemirror/lib/codemirror.css">
+ <link rel="stylesheet" href="cm_mode_test.css">
+ <!--<link rel="stylesheet" href="../doc/docs.css">-->
+
+ <script src="chrome://devtools/content/shared/sourceeditor/codemirror/codemirror.bundle.js"></script>
+ <script src="chrome://devtools/content/shared/sourceeditor/codemirror/keymap/emacs.js"></script>
+ <script src="chrome://devtools/content/shared/sourceeditor/codemirror/keymap/sublime.js"></script>
+ <script src="chrome://devtools/content/shared/sourceeditor/codemirror/keymap/vim.js"></script>
+
+ <style type="text/css">
+ .ok {color: #090;}
+ .fail {color: #e00;}
+ .error {color: #c90;}
+ .done {font-weight: bold;}
+ #progress {
+ background: #45d;
+ color: white;
+ text-shadow: 0 0 1px #45d, 0 0 2px #45d, 0 0 3px #45d;
+ font-weight: bold;
+ white-space: pre;
+ }
+ #testground {
+ visibility: hidden;
+ }
+ #testground.offscreen {
+ visibility: visible;
+ position: absolute;
+ left: -10000px;
+ top: -10000px;
+ }
+ .CodeMirror { border: 1px solid black; }
+ </style>
+ </head>
+ <body>
+ <h1>CodeMirror: VIM/Emacs tests</h1>
+
+ <p>A limited set of programmatic sanity tests for CodeMirror.</p>
+
+ <div style="border: 1px solid black; padding: 1px; max-width: 700px;">
+ <div style="width: 0px;" id=progress><div style="padding: 3px;">Ran <span id="progress_ran">0</span><span id="progress_total"> of 0</span> tests</div></div>
+ </div>
+ <p id=status>Please enable JavaScript...</p>
+ <div id=output></div>
+
+ <div id=testground></div>
+
+ <script src="driver.js"></script>
+ <script src="sublime_test.js"></script>
+ <script src="vim_test.js"></script>
+ <script src="emacs_test.js"></script>
+
+ <!-- Basic tests are in codemirror.html
+ <script src="cm_driver.js"></script>
+ <script src="cm_test.js"></script>
+ <script src="cm_comment_test.js"></script>
+ <script src="cm_doc_test.js"></script>
+ <script src="cm_driver.js"></script>
+ <script src="cm_emacs_test.js"></script>
+ <script src="cm_mode_test.js"></script>
+ <script src="cm_mode_javascript_test.js"></script>
+ <script src="cm_multi_test.js"></script>
+ <script src="cm_search_test.js"></script>
+ -->
+
+ <!-- These modes/addons are not used by Editor
+ <script src="doc_test.js"></script>
+ <script src="../mode/css/css.js"></script>
+ <script src="../mode/css/test.js"></script>
+ <script src="../mode/css/scss_test.js"></script>
+ <script src="../mode/xml/xml.js"></script>
+ <script src="../mode/htmlmixed/htmlmixed.js"></script>
+ <script src="../mode/ruby/ruby.js"></script>
+ <script src="../mode/haml/haml.js"></script>
+ <script src="../mode/haml/test.js"></script>
+ <script src="../mode/markdown/markdown.js"></script>
+ <script src="../mode/markdown/test.js"></script>
+ <script src="../mode/gfm/gfm.js"></script>
+ <script src="../mode/gfm/test.js"></script>
+ <script src="../mode/stex/stex.js"></script>
+ <script src="../mode/stex/test.js"></script>
+ <script src="../mode/xquery/xquery.js"></script>
+ <script src="../mode/xquery/test.js"></script>
+ <script src="../addon/mode/multiplex_test.js"></script>-->
+
+ <script>
+ window.onload = runHarness;
+ CodeMirror.on(window, 'hashchange', runHarness);
+
+ function esc(str) {
+ return str.replace(/[<&]/, function(ch) { return ch == "<" ? "&lt;" : "&amp;"; });
+ }
+
+ var output = document.getElementById("output"),
+ progress = document.getElementById("progress"),
+ progressRan = document.getElementById("progress_ran").childNodes[0],
+ progressTotal = document.getElementById("progress_total").childNodes[0];
+
+ var count = 0,
+ failed = 0,
+ skipped = 0,
+ bad = "",
+ running = false, // Flag that states tests are running
+ quit = false, // Flag to quit tests ASAP
+ verbose = false, // Adds message for *every* test to output
+ phantom = false,
+ Pos = CodeMirror.Pos; // Required for VIM tests
+
+ function runHarness(){
+ if (running) {
+ quit = true;
+ setStatus("Restarting tests...", '', true);
+ setTimeout(function(){runHarness();}, 500);
+ return;
+ }
+ filters = [];
+ verbose = false;
+ if (window.location.hash.substr(1)){
+ var strings = window.location.hash.substr(1).split(",");
+ while (strings.length) {
+ var s = strings.shift();
+ if (s === "verbose")
+ verbose = true;
+ else
+ filters.push(parseTestFilter(decodeURIComponent(s)));
+ }
+ }
+ quit = false;
+ running = true;
+ setStatus("Loading tests...");
+ count = 0;
+ failed = 0;
+ skipped = 0;
+ bad = "";
+ totalTests = countTests();
+ progressTotal.nodeValue = " of " + totalTests;
+ progressRan.nodeValue = count;
+ output.innerHTML = '';
+ document.getElementById("testground").innerHTML = "<form>" +
+ "<textarea id=\"code\" name=\"code\"></textarea>" +
+ "<input type=submit value=ok name=submit>" +
+ "</form>";
+ runTests(displayTest);
+ }
+
+ function setStatus(message, className, force){
+ if (quit && !force) return;
+ if (!message) throw("must provide message");
+ var status = document.getElementById("status").childNodes[0];
+ status.nodeValue = message;
+ status.parentNode.className = className;
+ }
+ function addOutput(name, className, code){
+ var newOutput = document.createElement("dl");
+ var newTitle = document.createElement("dt");
+ newTitle.className = className;
+ newTitle.appendChild(document.createTextNode(name));
+ newOutput.appendChild(newTitle);
+ var newMessage = document.createElement("dd");
+ newMessage.innerHTML = code;
+ newOutput.appendChild(newTitle);
+ newOutput.appendChild(newMessage);
+ output.appendChild(newOutput);
+ }
+ function displayTest(type, name, customMessage) {
+ var message = "???";
+ if (type != "done" && type != "skipped") ++count;
+ progress.style.width = (count * (progress.parentNode.clientWidth - 2) / totalTests) + "px";
+ progressRan.nodeValue = count;
+ if (type == "ok") {
+ message = "Test '" + name + "' succeeded";
+ if (!verbose) customMessage = false;
+ } else if (type == "skipped") {
+ message = "Test '" + name + "' skipped";
+ ++skipped;
+ if (!verbose) customMessage = false;
+ } else if (type == "expected") {
+ message = "Test '" + name + "' failed as expected";
+ if (!verbose) customMessage = false;
+ } else if (type == "error" || type == "fail") {
+ ++failed;
+ message = "Test '" + name + "' failed";
+ } else if (type == "done") {
+ if (failed) {
+ type += " fail";
+ message = failed + " failure" + (failed > 1 ? "s" : "");
+ } else if (count < totalTests) {
+ failed = totalTests - count;
+ type += " fail";
+ message = failed + " failure" + (failed > 1 ? "s" : "");
+ } else {
+ type += " ok";
+ message = "All passed";
+ if (skipped) {
+ message += " (" + skipped + " skipped)";
+ }
+ }
+ progressTotal.nodeValue = '';
+ customMessage = true; // Hack to avoid adding to output
+ }
+ if (window.mozilla_setStatus)
+ mozilla_setStatus(message, type, customMessage);
+ if (verbose && !customMessage) customMessage = message;
+ setStatus(message, type);
+ if (customMessage && customMessage.length > 0) {
+ addOutput(name, type, customMessage);
+ }
+ }
+ </script>
+ </body>
+</html>
diff --git a/devtools/client/shared/sourceeditor/test/css_autocompletion_tests.json b/devtools/client/shared/sourceeditor/test/css_autocompletion_tests.json
new file mode 100644
index 0000000000..a8f09e0741
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/css_autocompletion_tests.json
@@ -0,0 +1,106 @@
+{
+ "description": [
+ "Test states to be tested for css state machine in css-autocompleter.js file.",
+ "Test cases are of the following format:",
+ "[",
+ " [",
+ " line, # The line location of the cursor",
+ " ch # The column location of the cursor",
+ " ],",
+ " suggestions # Array of expected results",
+ "]"
+ ],
+ "tests": [
+ [[0, 10], []],
+ [
+ [4, 7],
+ [".devtools-menulist", ".devtools-toolbarbutton"]
+ ],
+ [
+ [5, 8],
+ [
+ "-moz-animation",
+ "-moz-animation-delay",
+ "-moz-animation-direction",
+ "-moz-animation-duration",
+ "-moz-animation-fill-mode",
+ "-moz-animation-iteration-count",
+ "-moz-animation-name",
+ "-moz-animation-play-state",
+ "-moz-animation-timing-function",
+ "-moz-appearance"
+ ]
+ ],
+ [
+ [12, 20],
+ ["none", "number-input"]
+ ],
+ [[12, 22], ["none"]],
+ [
+ [17, 22],
+ ["hsl", "hsla"]
+ ],
+ [
+ [19, 10],
+ [
+ "background",
+ "background-attachment",
+ "background-blend-mode",
+ "background-clip",
+ "background-color",
+ "background-image",
+ "background-origin",
+ "background-position",
+ "background-position-x",
+ "background-position-y",
+ "background-repeat",
+ "background-size"
+ ]
+ ],
+ [
+ [21, 9],
+ ["auto", "inherit", "initial", "revert", "revert-layer", "unset"]
+ ],
+ [
+ [25, 26],
+ [
+ ".devtools-toolbarbutton > tab",
+ ".devtools-toolbarbutton > hbox",
+ ".devtools-toolbarbutton > .toolbarbutton-menubutton-button"
+ ]
+ ],
+ [
+ [25, 31],
+ [".devtools-toolbarbutton > hbox.toolbarbutton-menubutton-button"]
+ ],
+ [
+ [29, 20],
+ [".devtools-menulist:after", ".devtools-menulist:active"]
+ ],
+ [
+ [30, 10],
+ [
+ "#devtools-anotherone",
+ "#devtools-itjustgoeson",
+ "#devtools-menu",
+ "#devtools-okstopitnow",
+ "#devtools-toolbarbutton",
+ "#devtools-yetagain"
+ ]
+ ],
+ [[39, 39], [".devtools-toolbarbutton:not([label]) > tab"]],
+ [
+ [43, 51],
+ [
+ ".devtools-toolbarbutton:not([checked=true]):hover:after",
+ ".devtools-toolbarbutton:not([checked=true]):hover:active"
+ ]
+ ],
+ [[58, 36], ["!important;"]],
+ [
+ [73, 42],
+ [":lang(", ":last-of-type", ":link", ":last-child"]
+ ],
+ [[77, 25], [".visible"]]
+ ]
+}
diff --git a/devtools/client/shared/sourceeditor/test/css_statemachine_testcases.css b/devtools/client/shared/sourceeditor/test/css_statemachine_testcases.css
new file mode 100644
index 0000000000..d2c51a8413
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/css_statemachine_testcases.css
@@ -0,0 +1,121 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+.devtools-toolbar {
+ -moz-appearance: none;
+ padding:4px 3px;border-bottom-width: 1px;
+ border-bottom-style: solid;
+}
+
+#devtools-menu.devtools-menulist,
+.devtools-toolbarbutton#devtools-menu {
+ -moz-appearance: none;
+ align-items: center;
+ min-width: 78px;
+ min-height: 22px;
+ text-shadow: 0 -1px 0 hsla(210,8%,5%,.45);
+ border: 1px solid hsla(210,8%,5%,.45);
+ border-radius: 3px;
+ background: linear-gradient(hsla(212,7%,57%,.35), hsla(212,7%,57%,.1)) padding-box;
+ box-shadow: 0 1px 0 hsla(210,16%,76%,.15) inset, 0 0 0 1px hsla(210,16%,76%,.15) inset, 0 1px 0 hsla(210,16%,76%,.15);
+ margin: 0 3px;
+ color: inherit;
+}
+
+.devtools-toolbarbutton > hbox.toolbarbutton-menubutton-button {
+ flex-direction: row;
+}
+
+.devtools-menulist:active,
+#devtools-toolbarbutton:focus {
+ outline: 1px dotted hsla(210,30%,85%,0.7);
+ outline-offset : -4px;
+}
+
+.devtools-toolbarbutton:not([label]) {
+ min-width: 32px;
+}
+
+.devtools-toolbarbutton:not([label]) > .toolbarbutton-text {
+ display: none;
+}
+
+.devtools-toolbarbutton:not([checked=true]):hover:active {
+ border-color: hsla(210,8%,5%,.6);
+}
+
+.devtools-menulist["open" ="true"],
+.devtools-toolbarbutton["open" = true],
+.devtools-toolbarbutton[checked= "true"] {
+ border-color: hsla(210,8%,5%,.6) !important;
+}
+
+.devtools-toolbarbutton["checked"="true"] {
+ color: hsl(208,100%,60%);
+}
+
+.devtools-toolbarbutton[checked=true]:hover {
+ background-color: transparent !important;
+}
+
+.devtools-toolbarbutton[checked=true]:hover:active {
+ background-color: hsla(210,8%,5%,.2) !important;
+}
+
+.devtools-toolbarbutton[type=menu-button] > .toolbarbutton-menubutton-button {
+ -moz-appearance: none;
+}
+
+.devtools-sidebar-tabs > tabs > tab:first-of-type {
+ margin-inline-start: -3px;
+}
+
+.devtools-sidebar-tabs > tabs > tab:not(:last-of-type) {
+ background-size: calc(100% - 2px) 100%, 1px 100%;
+}
+
+.hidden-labels-box:not(.visible) > label,
+.hidden-labels-box.visible ~ .hidden-labels-box > label:last-child {
+ display: none;
+}
+
+/* Maximize the size of the viewport when the window is small */
+@media (max-width: 800px) {
+ .category-name {
+ display: none;
+ }
+}
+
+@media all and (min-width: 300px) {
+ #error-box {
+ max-width: 50%;
+ margin: 0 auto;
+ background-image: url('chrome://global/skin/icons/information-32.png');
+ min-height: 36px;
+ padding-inline-start: 38px;
+ }
+
+ button {
+ width: auto !important;
+ min-width: 150px;
+ }
+
+ @keyframes downloadsIndicatorNotificationFinish {
+ from { opacity: 0; transform: scale(1); }
+ 20% {
+ opacity: .65;
+ animation-timing-function: ease-in;
+ } to { opacity: 0;
+ transform: scale(8); }
+ }
+}
+
+@keyframes smooth {
+ from { opacity: 0; transform: scale(1); }
+ 20% { opacity: .65; animation-timing-function: ease-in; }
+ to {
+ opacity : 0;
+ transform: scale(8);
+ }
+}
diff --git a/devtools/client/shared/sourceeditor/test/css_statemachine_tests.json b/devtools/client/shared/sourceeditor/test/css_statemachine_tests.json
new file mode 100644
index 0000000000..642c1107ae
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/css_statemachine_tests.json
@@ -0,0 +1,319 @@
+{
+ "description": [
+ "Test states to be tested for css state machine in css-autocompleter.js file.",
+ "Test cases are of the following format:",
+ "[",
+ " [",
+ " line, // The line location of the cursor",
+ " ch // The column locaiton of the cursor",
+ " ],",
+ " [",
+ " state, // one of CSS_STATES",
+ " selectorState, // one of SELECTOR_STATES",
+ " completing, // what is being completed",
+ " propertyName, // what property is being completed in case of value state",
+ " // or the current selector that is being completed",
+ " ]",
+ "]"
+ ],
+ "tests": [
+ [
+ [0, 10],
+ ["null", "", "", ""]
+ ],
+ [
+ [4, 3],
+ ["selector", "class", "de", ".de"]
+ ],
+ [
+ [5, 8],
+ ["property", "null", "-moz-a"]
+ ],
+ [
+ [5, 21],
+ ["value", "null", "no", "-moz-appearance"]
+ ],
+ [
+ [6, 18],
+ ["property", "null", "padding"]
+ ],
+ [
+ [6, 24],
+ ["value", "null", "3", "padding"]
+ ],
+ [
+ [6, 29],
+ ["property", "null", "bo"]
+ ],
+ [
+ [6, 50],
+ ["value", "null", "1p", "border-bottom-width"]
+ ],
+ [
+ [7, 24],
+ ["value", "null", "s", "border-bottom-style"]
+ ],
+ [
+ [9, 0],
+ ["null", "null", "", ""]
+ ],
+ [
+ [10, 6],
+ ["selector", "id", "devto", "#devto"]
+ ],
+ [
+ [10, 17],
+ ["selector", "class", "de", "#devtools-menu.de"]
+ ],
+ [
+ [11, 5],
+ ["selector", "class", "devt", ".devt"]
+ ],
+ [
+ [11, 30],
+ ["selector", "id", "devtoo", ".devtools-toolbarbutton#devtoo"]
+ ],
+ [
+ [12, 10],
+ ["property", "null", "-moz-app"]
+ ],
+ [
+ [16, 27],
+ ["value", "null", "hsl", "text-shadow"]
+ ],
+ [
+ [19, 24],
+ ["value", "null", "linear-gra", "background"]
+ ],
+ [
+ [19, 55],
+ ["value", "null", "hsl", "background"]
+ ],
+ [
+ [19, 79],
+ ["value", "null", "paddin", "background"]
+ ],
+ [
+ [20, 47],
+ ["value", "null", "ins", "box-shadow"]
+ ],
+ [
+ [22, 15],
+ ["value", "null", "inheri", "color"]
+ ],
+ [
+ [25, 26],
+ ["selector", "null", "", ".devtools-toolbarbutton > "]
+ ],
+ [
+ [25, 28],
+ ["selector", "tag", "hb", ".devtools-toolbarbutton > hb"]
+ ],
+ [
+ [25, 41],
+ [
+ "selector",
+ "class",
+ "toolbarbut",
+ ".devtools-toolbarbutton > hbox.toolbarbut"
+ ]
+ ],
+ [
+ [29, 21],
+ ["selector", "pseudo", "ac", ".devtools-menulist:ac"]
+ ],
+ [
+ [30, 27],
+ ["selector", "pseudo", "foc", "#devtools-toolbarbutton:foc"]
+ ],
+ [
+ [31, 18],
+ ["value", "null", "dot", "outline"]
+ ],
+ [
+ [32, 25],
+ ["value", "null", "-4p", "outline-offset"]
+ ],
+ [
+ [35, 26],
+ ["selector", "pseudo", "no", ".devtools-toolbarbutton:no"]
+ ],
+ [
+ [35, 28],
+ ["selector", "null", "not", ""]
+ ],
+ [
+ [35, 30],
+ ["selector", "attribute", "l", "[l"]
+ ],
+ [
+ [39, 46],
+ [
+ "selector",
+ "class",
+ "toolba",
+ ".devtools-toolbarbutton:not([label]) > .toolba"
+ ]
+ ],
+ [
+ [43, 39],
+ ["selector", "value", "tr", "[checked=tr"]
+ ],
+ [
+ [43, 47],
+ [
+ "selector",
+ "pseudo",
+ "hov",
+ ".devtools-toolbarbutton:not([checked=true]):hov"
+ ]
+ ],
+ [
+ [43, 53],
+ [
+ "selector",
+ "pseudo",
+ "act",
+ ".devtools-toolbarbutton:not([checked=true]):hover:act"
+ ]
+ ],
+ [
+ [47, 22],
+ ["selector", "attribute", "op", ".devtools-menulist[op"]
+ ],
+ [
+ [47, 33],
+ ["selector", "value", "tr", ".devtools-menulist[open =tr"]
+ ],
+ [
+ [48, 38],
+ ["selector", "value", "tr", ".devtools-toolbarbutton[open = tr"]
+ ],
+ [
+ [49, 40],
+ ["selector", "value", "true", ".devtools-toolbarbutton[checked= true"]
+ ],
+ [
+ [53, 34],
+ ["selector", "value", "=", ".devtools-toolbarbutton[checked="]
+ ],
+ [
+ [58, 38],
+ ["value", "null", "!impor", "background-color"]
+ ],
+ [
+ [61, 41],
+ ["selector", "pseudo", "hov", ".devtools-toolbarbutton[checked=true]:hov"]
+ ],
+ [
+ [65, 47],
+ [
+ "selector",
+ "class",
+ "to",
+ ".devtools-toolbarbutton[type=menu-button] > .to"
+ ]
+ ],
+ [
+ [69, 44],
+ [
+ "selector",
+ "pseudo",
+ "first-of",
+ ".devtools-sidebar-tabs > tabs > tab:first-of"
+ ]
+ ],
+ [
+ [73, 45],
+ ["selector", "pseudo", "last", ":last"]
+ ],
+ [
+ [77, 27],
+ ["selector", "class", "vis", ".vis"]
+ ],
+ [
+ [78, 34],
+ ["selector", "class", "hidd", ".hidden-labels-box.visible ~ .hidd"]
+ ],
+ [
+ [83, 5],
+ ["media", "null", "medi"]
+ ],
+ [
+ [83, 22],
+ ["media", "null", "800"]
+ ],
+ [
+ [84, 9],
+ ["selector", "class", "catego", ".catego"]
+ ],
+ [
+ [89, 9],
+ ["media", "null", "al"]
+ ],
+ [
+ [90, 6],
+ ["selector", "id", "err", "#err"]
+ ],
+ [
+ [93, 11],
+ ["property", "null", "backgro"]
+ ],
+ [
+ [98, 6],
+ ["selector", "tag", "butt", "butt"]
+ ],
+ [
+ [99, 22],
+ ["value", "null", "!impor", "width"]
+ ],
+ [
+ [103, 5],
+ ["keyframes", "null", "ke"]
+ ],
+ [
+ [104, 7],
+ ["frame", "null", "fro"]
+ ],
+ [
+ [104, 15],
+ ["property", "null", "opac"]
+ ],
+ [
+ [104, 29],
+ ["property", "null", "transf"]
+ ],
+ [
+ [104, 38],
+ ["value", "null", "scal", "transform"]
+ ],
+ [
+ [105, 8],
+ ["frame", "null", ""]
+ ],
+ [
+ [113, 6],
+ ["keyframes", "null", "keyfr"]
+ ],
+ [
+ [114, 4],
+ ["frame", "null", "fr"]
+ ],
+ [
+ [115, 3],
+ ["frame", "null", "2"]
+ ],
+ [
+ [117, 8],
+ ["property", "null", "opac"]
+ ],
+ [
+ [117, 16],
+ ["value", "null", "0", "opacity"]
+ ],
+ [
+ [121, 0],
+ ["null", "", ""]
+ ]
+ ]
+}
diff --git a/devtools/client/shared/sourceeditor/test/head.js b/devtools/client/shared/sourceeditor/test/head.js
new file mode 100644
index 0000000000..7d11fbe475
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/head.js
@@ -0,0 +1,195 @@
+/* Any copyright is dedicated to the Public Domain.
+ http://creativecommons.org/publicdomain/zero/1.0/ */
+
+/* exported promiseWaitForFocus, setup, ch, teardown, loadHelperScript,
+ limit, ch, read, codemirrorSetStatus */
+
+"use strict";
+
+// shared-head.js handles imports, constants, and utility functions
+Services.scriptloader.loadSubScript(
+ "chrome://mochitests/content/browser/devtools/client/shared/test/shared-head.js",
+ this
+);
+
+const Editor = require("resource://devtools/client/shared/sourceeditor/editor.js");
+
+function promiseWaitForFocus(el) {
+ return new Promise(resolve => waitForFocus(resolve, el));
+}
+
+async function setup(additionalOpts = {}) {
+ try {
+ const opt = "chrome,titlebar,toolbar,centerscreen,resizable,dialog=no";
+ const win = Services.ww.openWindow(
+ null,
+ CHROME_URL_ROOT + "head.xhtml",
+ "_blank",
+ opt,
+ null
+ );
+ const opts = {
+ value: "Hello.",
+ lineNumbers: true,
+ foldGutter: true,
+ gutters: [
+ "CodeMirror-linenumbers",
+ "breakpoints",
+ "CodeMirror-foldgutter",
+ ],
+ cssProperties: getClientCssProperties(),
+ ...additionalOpts,
+ };
+
+ await once(win, "load");
+ await promiseWaitForFocus(win);
+
+ const box = win.document.querySelector("box");
+ const editor = new Editor(opts);
+ await editor.appendTo(box);
+
+ return {
+ ed: editor,
+ win,
+ edWin: editor.container.contentWindow.wrappedJSObject,
+ };
+ } catch (o_O) {
+ ok(false, o_O.message);
+ return null;
+ }
+}
+
+function ch(exp, act, label) {
+ is(exp.line, act.line, label + " (line)");
+ is(exp.ch, act.ch, label + " (ch)");
+}
+
+function teardown(ed, win) {
+ ed.destroy();
+ win.close();
+
+ while (gBrowser.tabs.length > 1) {
+ gBrowser.removeCurrentTab();
+ }
+ finish();
+}
+
+/**
+ * Some tests may need to import one or more of the test helper scripts.
+ * A test helper script is simply a js file that contains common test code that
+ * is either not common-enough to be in head.js, or that is located in a
+ * separate directory.
+ * The script will be loaded synchronously and in the test's scope.
+ * @param {String} filePath The file path, relative to the current directory.
+ * Examples:
+ * - "helper_attributes_test_runner.js"
+ */
+function loadHelperScript(filePath) {
+ const testDir = gTestPath.substr(0, gTestPath.lastIndexOf("/"));
+ Services.scriptloader.loadSubScript(testDir + "/" + filePath, this);
+}
+
+/**
+ * This method returns the portion of the input string `source` up to the
+ * [line, ch] location.
+ */
+function limit(source, [line, char]) {
+ line++;
+ const list = source.split("\n");
+ if (list.length < line) {
+ return source;
+ }
+ if (line == 1) {
+ return list[0].slice(0, char);
+ }
+ return [...list.slice(0, line - 1), list[line - 1].slice(0, char)].join("\n");
+}
+
+function read(url) {
+ const scriptableStream = Cc[
+ "@mozilla.org/scriptableinputstream;1"
+ ].getService(Ci.nsIScriptableInputStream);
+
+ const channel = NetUtil.newChannel({
+ uri: url,
+ loadUsingSystemPrincipal: true,
+ });
+ const input = channel.open();
+ scriptableStream.init(input);
+
+ let data = "";
+ while (input.available()) {
+ data = data.concat(scriptableStream.read(input.available()));
+ }
+ scriptableStream.close();
+ input.close();
+
+ return data;
+}
+
+/**
+ * This function is called by the CodeMirror test runner to report status
+ * messages from the CM tests.
+ * @see codemirror.html
+ */
+function codemirrorSetStatus(statusMsg, type, customMsg) {
+ switch (type) {
+ case "expected":
+ case "ok":
+ ok(1, statusMsg);
+ break;
+ case "error":
+ case "fail":
+ ok(0, statusMsg);
+ break;
+ default:
+ info(statusMsg);
+ break;
+ }
+
+ if (customMsg && typeof customMsg == "string" && customMsg != statusMsg) {
+ info(customMsg);
+ }
+}
+
+async function runCodeMirrorTest(uri) {
+ const actorURI =
+ "chrome://mochitests/content/browser/devtools/client/shared/sourceeditor/test/CodeMirrorTestActors.sys.mjs";
+
+ const { CodeMirrorTestParent } = ChromeUtils.importESModule(actorURI);
+
+ ChromeUtils.registerWindowActor("CodeMirrorTest", {
+ parent: {
+ esModuleURI: actorURI,
+ },
+ child: {
+ esModuleURI: actorURI,
+ events: {
+ DOMWindowCreated: {},
+ },
+ },
+ });
+
+ const donePromise = new Promise(resolve => {
+ CodeMirrorTestParent.setCallback((name, data) => {
+ switch (name) {
+ case "setStatus":
+ const { statusMsg, type, customMsg } = data;
+ codemirrorSetStatus(statusMsg, type, customMsg);
+ break;
+ case "done":
+ resolve(!data.failed);
+ break;
+ }
+ });
+ });
+
+ await addTab(uri);
+ const result = await donePromise;
+ ok(result, "CodeMirror tests all passed");
+ while (gBrowser.tabs.length > 1) {
+ gBrowser.removeCurrentTab();
+ }
+
+ ChromeUtils.unregisterWindowActor("CodeMirrorTest");
+}
diff --git a/devtools/client/shared/sourceeditor/test/head.xhtml b/devtools/client/shared/sourceeditor/test/head.xhtml
new file mode 100644
index 0000000000..4e0fe90812
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/test/head.xhtml
@@ -0,0 +1,5 @@
+<?xml version='1.0'?>
+<?xml-stylesheet href='chrome://global/skin/global.css'?>
+<window xmlns='http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul' title='Editor' width='600' height='500'>
+<box flex='1'/>
+</window>
diff --git a/devtools/client/shared/sourceeditor/wasm.js b/devtools/client/shared/sourceeditor/wasm.js
new file mode 100644
index 0000000000..ed3ef4df63
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/wasm.js
@@ -0,0 +1,93 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+const wasmparser = require("resource://devtools/client/shared/vendor/WasmParser.js");
+const wasmdis = require("resource://devtools/client/shared/vendor/WasmDis.js");
+
+const wasmStates = new WeakMap();
+
+function getWasmText(subject, data) {
+ const parser = new wasmparser.BinaryReader();
+ parser.setData(data.buffer, 0, data.length);
+ const dis = new wasmdis.WasmDisassembler();
+ dis.addOffsets = true;
+ const done = dis.disassembleChunk(parser);
+ let result = dis.getResult();
+ if (result.lines.length === 0) {
+ result = { lines: ["No luck with wast conversion"], offsets: [0], done };
+ }
+
+ const offsets = result.offsets,
+ lines = [];
+ for (let i = 0; i < offsets.length; i++) {
+ lines[offsets[i]] = i;
+ }
+
+ wasmStates.set(subject, { offsets, lines });
+
+ return { lines: result.lines, done: result.done };
+}
+
+function getWasmLineNumberFormatter(subject) {
+ const codeOf0 = 48,
+ codeOfA = 65;
+ const buffer = [
+ codeOf0,
+ codeOf0,
+ codeOf0,
+ codeOf0,
+ codeOf0,
+ codeOf0,
+ codeOf0,
+ codeOf0,
+ ];
+ let last0 = 7;
+ return function (number) {
+ const offset = lineToWasmOffset(subject, number - 1);
+ if (offset === undefined) {
+ return "";
+ }
+ let i = 7;
+ for (let n = offset | 0; n !== 0 && i >= 0; n >>= 4, i--) {
+ const nibble = n & 15;
+ buffer[i] = nibble < 10 ? codeOf0 + nibble : codeOfA - 10 + nibble;
+ }
+ for (let j = i; j > last0; j--) {
+ buffer[j] = codeOf0;
+ }
+ last0 = i;
+ return String.fromCharCode.apply(null, buffer);
+ };
+}
+
+function isWasm(subject) {
+ return wasmStates.has(subject);
+}
+
+function lineToWasmOffset(subject, number) {
+ const wasmState = wasmStates.get(subject);
+ if (!wasmState) {
+ return undefined;
+ }
+ let offset = wasmState.offsets[number];
+ while (offset === undefined && number > 0) {
+ offset = wasmState.offsets[--number];
+ }
+ return offset;
+}
+
+function wasmOffsetToLine(subject, offset) {
+ const wasmState = wasmStates.get(subject);
+ return wasmState.lines[offset];
+}
+
+module.exports = {
+ getWasmText,
+ getWasmLineNumberFormatter,
+ isWasm,
+ lineToWasmOffset,
+ wasmOffsetToLine,
+};
diff --git a/devtools/client/shared/sourceeditor/webpack.config.js b/devtools/client/shared/sourceeditor/webpack.config.js
new file mode 100644
index 0000000000..4754dfff58
--- /dev/null
+++ b/devtools/client/shared/sourceeditor/webpack.config.js
@@ -0,0 +1,61 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+"use strict";
+
+const path = require("path");
+
+module.exports = (env, argv) => {
+ return {
+ bail: true,
+ entry: [
+ "./codemirror/addon/dialog/dialog.js",
+ "./codemirror/addon/search/searchcursor.js",
+ "./codemirror/addon/search/search.js",
+ "./codemirror/addon/search/match-highlighter.js",
+ "./codemirror/addon/edit/matchbrackets.js",
+ "./codemirror/addon/edit/closebrackets.js",
+ "./codemirror/addon/comment/comment.js",
+ "./codemirror/addon/accessibleTextarea.js",
+ "./codemirror/mode/javascript/javascript.js",
+ "./codemirror/mode/xml/xml.js",
+ "./codemirror/mode/css/css.js",
+ "./codemirror/mode/clojure/clojure.js",
+ "./codemirror/mode/haxe/haxe.js",
+ "./codemirror/mode/http/http.js",
+ "./codemirror/mode/htmlmixed/htmlmixed.js",
+ "./codemirror/mode/jsx/jsx.js",
+ "./codemirror/mode/coffeescript/coffeescript.js",
+ "./codemirror/mode/elm/elm.js",
+ "./codemirror/mode/clike/clike.js",
+ "./codemirror/mode/rust/rust.js",
+ "./codemirror/mode/wasm/wasm.js",
+ "./codemirror/addon/selection/active-line.js",
+ "./codemirror/addon/edit/trailingspace.js",
+ "./codemirror/addon/fold/foldcode.js",
+ "./codemirror/addon/fold/brace-fold.js",
+ "./codemirror/addon/fold/comment-fold.js",
+ "./codemirror/addon/fold/xml-fold.js",
+ "./codemirror/addon/fold/foldgutter.js",
+ "./codemirror/addon/runmode/runmode.js",
+ "./codemirror/addon/display/placeholder.js",
+ "./codemirror/lib/codemirror.js",
+ ],
+ optimization: {
+ minimize: !(argv.optimization && argv.optimization.minimizer === "false"),
+ },
+ output: {
+ path: path.resolve(__dirname, "./codemirror/"),
+ filename: "codemirror.bundle.js",
+ libraryTarget: "var",
+ library: "CodeMirror",
+ },
+ resolve: {
+ alias: {
+ "resource://devtools": "devtools",
+ },
+ modules: [path.resolve(__dirname, "../../../..")],
+ },
+ };
+};